Dec-07-2020, 03:13 AM
Hello Pythonistas!
I’m learning the insertion sort algorithm using Joe James’ terrific YouTube tutorial.
He’s got some resources on GitHub for reference which are enormously fun to play with.
Here is one of the variations of the three insertion sort algorithm he has:
I experimented by trying to spread out that one line into two separate ones like this:
I’m learning the insertion sort algorithm using Joe James’ terrific YouTube tutorial.
He’s got some resources on GitHub for reference which are enormously fun to play with.
Here is one of the variations of the three insertion sort algorithm he has:
def insertion_sort(A): for i in range(1, len(A)): for j in range(i-1, -1, -1): if A[j] > A[j+1]: A[j], A[j+1] = A[j+1], A[j] else: break A = [5,9,1,2,4,8,6,3,7] print(A) insertion_sort(A) print(A)Here is the correct and expected sorted output:
Output:[1, 2, 3, 4, 5, 6, 7, 8, 9]
I’m struggling with line five. Could someone please clarify what is going on there?I experimented by trying to spread out that one line into two separate ones like this:
def insertion_sort_Drone4four(A): for i in range(1, len(A)): for j in range(i-1, -1, -1): if A[j] > A[j+1]: A[j] = A[j+1] A[j+1] = A[j] else: breakBut then the output isn’t sorted. Instead I get this:
Output:[1, 1, 1, 2, 3, 3, 3, 3, 7]
What is going on in the original script at line 5? Also: How might you people rewrite it to spread out that line to make it easier to read for a novice such as myself?