I was trying to implement an Insertion Sort code using a sample code provided using a lecture, and despite placing the code word for word, the Insertion Sort function does not sort an array by ascending order. The code instead gives a duplicate number, say 2 within the array.
I've tried to adjust the end value for the range function from n-1 to n, but all it does is give me 2 arrays, both arrays with at least 1 number duplicated. Changing the position of array[j] and array[j - 1] under the while loop only changes the duplicate numbers from 2 to 3.
Nothing seems to sort the array to give the answer [1,2,3] and I have no idea what exactly is wrong with this code, so why is Insertion Sort giving me duplicates instead of properly sorting the array?
The code below is what I was using.
def function insertion_sort(array):
n = len(array)
for i in range(1, n-1):
j = i #j is inner index, i is inner index
temporary = array[j]
while (j > 0) and (array[j] < array[j-1]):
array[j]= array[j - 1]#shift right
j = j - 1 #move left
print(array)
array[j] = temporary #save to final position
array = [3,2,1] #test case
insertion_sort(array)
Result when n-1 is changed to n:
[3, 3, 1] #3 is duplicated, 2 has disappeared
Result when position of array is swapped:
[2, 2, 1] #2 is duplicated, 3 has disappeared
I think your code is valid. But note that currently your implementation sorts number in a descending order due to this comparison:
array[j] < array[j-1]It should be reverted to have it sort arrays in a ascending order.Your problem is with with understanding what your code does. You talk about what it gives you, but actually your functions 'gives' you nothing. You only have an intermediate result printed out (just before the assignement of the temporary value back, this is why you think you get duplicates). You should rather displace this print() after all processing or have your function return something.
Try using various test cases to pin out what might be a problem in your code. I think also since you are learning that you don't fully grasp what the code is doing. Try reading a bit about algorithmics and python.