# Python: InsertionSort algorithm

48
49 Insertion Sort algorithm explained in animated demo, with example Python 3.3 code implementation.

PYTHON SORTING ALGORITHMS
► Insertion Sort
► Selection Sort
► Bubble Sort
► Merge Sort
► Quick Sort

► Code on GitHub
► Subscribe to my Channel
► Thank me on Patreon:

Nguồn: https://quydinh.com

Xem thêm bài viết khác: https://quydinh.com/cong-nghe

1. You have put incorrect code in the video!! It should be FOR j in range(I-1, -1, -1):

2. def insertionsort(A):

for i in range(0,len(A)):

curnum=A[i]

for j in range(i-1,-1,-1):

if A[j]>curnum and j==0:

A[j+1]=A[j]

A[j]=curnum

elif A[j]>curnum:

A[j+1]=A[j]

else:

A[j+1]=curnum

break

return A
this is the code for shifting.. the shifting code given in video is wrong

3. That while loop cleared all my doubts

4. Wait… isn't this is bubble sort?!

5. wait who's joe?

6. Ok, this is not the insertion sort I read in geeksforgeeks, is it not supposed to INSERT a value to the beginning in a comparison? the insertion sort I did as practice before checking this video was fast, then I come here, and I find TOO much swapping and no INSERT in the algorithm, sight, oh well, I saving these examples anyway XD, by the way, actually inserting the numbers is faster than swapping them XD, the one I wrote is 2x faster than the curNum one case XD.

7. what will it return?? babaji ka thullu??

8. This is incorrent…

9. For those who are struggling to keep up with this video, this is the correct and working code for the nested loop version:
def insertion(lst):

for i in range(1, len(lst)):

print(i)

for j in range(i-1,-1,-1):

print(j)

if lst[j]>lst[j+1]:

lst[j],lst[j+1]=lst[j+1],lst[j]

print(lst)

else:

break

return lst

# "Optimized" insertion sort algo based on nesterd loops
def insertion(A):

for i in range(1, len(A)):

curNum=A[i]

for j in range(i-1, -1, -1):

if A[j] > curNum:

A[j+1] = A[j]

A[j]=curNum

else:

break

return A

#The code below will t

10. The last example of code does not work correctly.

11. wrong ,you should type
else:
j+=1
break
A[j]=curNum

12. There are errors. I took time to try to fix my algorithm, here's what I have for my insertion sort algorithm: (works after a few tests)

def insertion_sort(list):

for i in range(1, len(list)):

currentNumber = list[i]

for j in range(i-1, -1, -1):

if(currentNumber <= list[j] and j == 0):

list[(j+1)] = list[j]

list[j] = currentNumber

break

if(list[j] > currentNumber):

list[j+1] = list[j]

else:

list[j+1] = currentNumber

break

13. no its going on infinite. …. mergesort(A,first,mid) in mergesort2() is not correct

14. Incredible video. Exactly what I was looking for!

15. Too many errors – needs redoing. The while version should use j = i and condition j > 0. as it is, one element is left unsorted. Also the for loop version has a problem as mentioned in comments. Shame to spoil good footage with confusing inaccuracies.

16. this is true but it will not fix the first index at the first solution using insertion sort
to do this correctly you should implement :
for j in range(i-1,-1,-1):
because python does not take the last index in the range

17. consideration : The left of the current number is already sorted
You can use binary search method for comparision and then swap that will decrease time complexity
O(n^2) —–> O(nlogn)

18. Vansh Gulati official

sir there is an error in the first code as in there 0th index will not be included hence first element would not be sorted it should be – for j in range(i-1,-1,-1) thanks sir for posting such videos and making people good learners you have helped me to gain interest and made me capable of finding bugs
xoxoxoxo 🙂

19. Hi Joe, great video! However, I found an issue in your optimized code around 4:28:
You wrote:
for j in range(i-1, 0, -1):
if A[j] > curNum:
A[j+1] = A[j]

"A[j+1] = A[j] " is not correct. This will cause over-wright the element A[j+1] by A[j]. A swap is more appropriate as below. Of course, this way there is no more optimization as you are trying to do:
for j in range(i-1, 0, -1):
if A[j] > curNum:
A[j+1], A[j] = A[j], A[j+1]

20. At 2:27 it will be
for j in range(i-1,-1,-1):

21. Kerod Fresenbet Gebremedhin

set 0 in the for loop parameter for the ending index to -1 and it should work fine

22. I was able to code an Insertion sort with a running time of O(n), it's on my github account for those who want to check it out!
https://github.com/Jamilnineteen91 Edit: I was an idiot… ignore this…lol…

23. Swaaaaap
😂 😂 😂
No offence

24. Please put the code in the description so that we can directly copy paste it 😉

25. isnt this just bubblesort

26. return(A)
print(insertionsort(MyList))

MyList = [1,3,5,7,2,1,2,1,6,9,9,7,6,55,99]

To get an output

27. Hey joe, i have a question here, inside the second "for loop", why we using "j+1" instead of "i", i tried change "j+1" with "i" and the result is wrong. can you explain it to me, why it becomes wrong when i use "i" instead of "j+1" , but the value of "i" and "j+1" is actually the same ???

28. to make the code in the video works(if you don't like the one in the GitHub):
——–
in line 5:
if A[j] > curNum:
A[j+1] = A[j]

######add an if statement, and become:
if A[j] > curNum:
A[j+1] = A[j]
if j == 0:
A[j] = curNum

reason:
the list: A = [7, 8, 5, 4, 9, 2]
in the outer range, when i =2, curNum = 5
j = i – 1 = 2-1 = 1
—#####first loop of range for j:
A[j] = 8 > curNum=5 —> [7, 8, 8, 4,9,2]
–#######second loop for j:
j = 0
A[j] = 7 > curNum = 5 —> [7,7,8,4,9,2]
and the program ends ( same for the rest of the list, that's why u may get a lot of 7s), it doesn't have a chance to put the curNum into the position it suppose to be
so I used:
if j == 0:
A[j] = curNum
works fine!!

29. thank you

30. Fix for last optimized algorithm
https://github.com/joeyajames/Python/blob/master/SortingAlgorithms.py
# optimized – shifts instead of swapping
def insertion_sort3(A):
for i in range(1, len(A)):
curNum = A[i]
k = 0
for j in range(i-1, -2, -1):
k = j
if A[j] > curNum:
A[j+1] = A[j]
else:
break
A[k+1] = curNum

31. thanks help a lot

32. Python tutorial in hindi

tanks Joe james

33. It shifting one does not work for[6, 5, 4, 3, 2, 1]

34. i have tried both method but i don't see any major difference in total time taken just 0.01 or 0.02 sec difference.

35. 3:19 swapping fundamentals but he uses 'shifting' because it's quicker

36. Nice Work, but I am a bit stuck on the part where you optimize the code: I used a list with elements [ 7,5,3,2,1,4,6,9,8] and I get the output as [7,7,7,7,7,7,7,8,9]. Can you help me out

37. thanks, those videos are very helpful!

38. thank you Joe James for these lovely tutorials you have helped me a lot in getting better at Python

39. what is the janky looking '-1' edited into the video?

40. These videos are incredibly helpful. Thank you for helping make this information available!

41. Hey Joe, the optimized code at [4:35] doesn't seem to work correctly. Can you confirm if there's a mistake in the video? I checked your github, the there the code looks different from the one you showed in here.

42. Hi James, great video, now from my understanding this insertion Sort code would sort a linked list, how would I change it so that it sorts an array?

43. Been trying this several times to sort in ascending order and below is code which worked for me, hope it helps someone else. By the way Joe thanks for the excellent videos.

def insertion_sort(A):
for i in range(1, len(A)+1):
for j in range(i-1, 0, -1 ):
if A[j] > A[j-1]:
break
else:
A[j-1], A[j] = A[j], A[j-1]
return A

44. Thanks, I did the code and realized the first index was never sorted. Took me a while to solve the issue on my own, but later realized that the answer was down in the comment section lol.

45. Никола Пауновић

I may be missing something, but this code is not working for me.

def insertion_sort(A):
for i in range(1, len(A)):
for j in range(i-1, 0, -1):
if A[j] > A[j+1]:
A[j], A[j+1] = A[j+1], A[j]
else:
break

I even tried copy/paste from your github account, but still doesn't appear to work.

46. What if you have numbers with more than 1 digit? For example this algorithm sorts my numbers in a way that 33,000 seems smaller than 679 because 679 starts with the 6 which is bigger than 3. Therefore sorting my numbers [33000,679]. How would you solve this?