insertion-sort

Insertion sort python algorithm: Why do we subtract 1 from i?

Insertion sort python algorithm: Why do we subtract 1 from i? Question: Here is the code: list_a = [3,2,5,7,4,1] def insertion_sort(list_a): indexing_length = range(1,len(list_a)) for i in indexing_length: value_to_sort = list_a[i] while list_a[i-1] > value_to_sort and i>0: list_a[i], list_a[i-1] = list_a[i-1], list_a[i] i = i – 1 return list_a I understand the logic to the …

Total answers: 4

Made a code for insertion sort, declared a sorted and an unsorted array, but the unsorted array is output as a sorted array at the end

Made a code for insertion sort, declared a sorted and an unsorted array, but the unsorted array is output as a sorted array at the end Question: def InsSort(myList): UBound = len(myList) for i in range(1,UBound): NextItem = myList[i] position = i – 1 while position>=0 and myList[position]>NextItem: myList[position+1] = myList[position] position = position – …

Total answers: 1

How do I add a swap and comparisons counter in my code?

How do I add a swap and comparisons counter in my code? Question: For a list of numbers, I am trying to sort them in ascending order. At the same time, I need to add a swap and comparison counter to my output. For the most part, how do I add the incrementation in my …

Total answers: 1

Insertion Sort Python

Insertion Sort Python Question: I have implemented insertion sort in python and was wondering how to determine the complexity of the algorithm. Is this an inefficient way of implementing insertion sort? To me, this seems like the most readable algorithm. import random as rand source = [3,1,0,10,20,2,1] target = [] while len(source)!=0: if len(target) ==0: …

Total answers: 4