Python: Insertion Sort algorithm

แชร์
ฝัง
  • เผยแพร่เมื่อ 27 พ.ย. 2024

ความคิดเห็น • 126

  • @hunterrees
    @hunterrees 2 ปีที่แล้ว +24

    A quick tip for anyone: you don’t need a temp variable when swapping two variables. In python, you can write the following code:
    x, y = y, x
    This swaps both of the variables in one line because python allows recursive referencing of variables, and it allows multiple identifiers to be assigned in one line.

  • @shivamkumarrai3253
    @shivamkumarrai3253 4 ปีที่แล้ว +23

    2:57
    correction required:: for j in range(i-1,-1,-1):
    check for test case:: A=[10,9,8,5,3,7,92,185,78,1,0,65]

    • @amorgamer-he9ym
      @amorgamer-he9ym 9 หลายเดือนก่อน

      thank you for this correction because i found same problem but i couldn't solve it so thank you

  • @randyrichardson6953
    @randyrichardson6953 9 ปีที่แล้ว +12

    Thanks for all these videos, Joe. I've been programming in Python for about a year now, but none of the books I've read teach anything about algorithms or data structures. I finally feel like I'm learning REAL computer science. Cheers.

    • @jst8922
      @jst8922 11 หลายเดือนก่อน

      Bhasin H. Data Structures with Python...and Algorithms in Python 2023
      Educohack Team. Python-Based Data Structures and Algorithms 2024.pdf

  • @soseofficial3923
    @soseofficial3923 3 ปีที่แล้ว +4

    best teacher of sorting algorithms in python i found on youtube so far... Thank you Joe James.

  • @vanshgulati4808
    @vanshgulati4808 5 ปีที่แล้ว +84

    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 :)

    • @Aflesyn
      @Aflesyn 5 ปีที่แล้ว +2

      лол, не я одна заметила

    • @anuragdhyani1712
      @anuragdhyani1712 5 ปีที่แล้ว +2

      yes , you are absolutely correct my dear friend !

    • @mananpatel2642
      @mananpatel2642 5 ปีที่แล้ว +1

      good one

    • @Aaron_17
      @Aaron_17 4 ปีที่แล้ว

      Hi there, do you mind please explaining to me your for loop which you coded above? I know that your code works I just don't understand the second argument in your range function. Isn't it true that the second argument in the range function refers to where you want the iteration to stop? So it would be 'range[start, stop, step]' And isn't it true that the value "-1" refers to the last item in a list? So if you have "-1" as the second argument in your range function, doesn't that mean you want the iteration to stop at the last item in the list? Your code works so I'm obviously misunderstanding something. If you could explain to me why I'm wrong I'd very much appreciate it.

    • @aditya4974
      @aditya4974 4 ปีที่แล้ว +2

      @@Aaron_17 if you start from 0th index and move in the forward direction, then Yes, -1 refers to the last element of the list.
      However, if you start from (n-1)th index and move in the reverse direction (here n is the size of the list), then -1 means that you want to iterate from n-1 to 0, inclusive.

  • @sathyanarayanankulasekaran5928
    @sathyanarayanankulasekaran5928 3 ปีที่แล้ว +7

    Thanks for the videos Sir, two corrections required in the code are , Arr[j]=currNum inside the if loop so that the currnum value is retained, second is for range is (i-1,-1,-1)

    • @baranpolat2910
      @baranpolat2910 2 ปีที่แล้ว

      can you please send the code of the fixed version of the last example I don't get it

    • @aarth2022
      @aarth2022 ปีที่แล้ว +3

      @@baranpolat2910
      def insertion_sort(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:
      A[j+1] = curNum
      break

  • @hrithikrana7788
    @hrithikrana7788 3 ปีที่แล้ว +2

    this video is still usefull after 5 years........... thank you sir , great explanation

  • @AH-xb7eb
    @AH-xb7eb 9 ปีที่แล้ว +3

    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.

  • @yourdadishere
    @yourdadishere 3 ปีที่แล้ว +1

    Yeah, really great job, man. I know this is a bit old but it's still a goodie. Having been an educator in a different area of study for many years, I honestly have to say that what charmed me the most was that you explained each line and what was happening in the algorithm by referring to what is left or right. So many other youtubers have forgotten to keep this compass rose available for listeners and simple rushed through the code.

    • @oggiai
      @oggiai  3 ปีที่แล้ว

      Thanks.

  • @drustan6890
    @drustan6890 5 ปีที่แล้ว +4

    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

    • @Tdigger
      @Tdigger 4 ปีที่แล้ว

      thank you very much

  • @abhishekparida22
    @abhishekparida22 3 ปีที่แล้ว +5

    Thank you for the video.
    I think the stop parameter of the second for-loop should be -1, not 0.
    for j in range(i-1, -1, -1)

    • @ChunkiFTW
      @ChunkiFTW 2 ปีที่แล้ว +1

      I think so too, because if it is 0 that means we always assume the first number is the smallest. Good catch, I was wondering what was going on.

  • @francisssemwanga3014
    @francisssemwanga3014 8 ปีที่แล้ว +3

    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

  • @kerodfresenbetgebremedhin1881
    @kerodfresenbetgebremedhin1881 5 ปีที่แล้ว +2

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

  • @oggiai
    @oggiai  9 ปีที่แล้ว

    See code on my GitHub repository here, github.com/joeyajames/Python

  • @darshankokal4670
    @darshankokal4670 3 ปีที่แล้ว

    Fast and simple to understand!
    Thanks for making such wonderful content!! 😃

  • @JohnnyMetz
    @JohnnyMetz 5 ปีที่แล้ว +2

    Incredible video. Exactly what I was looking for!

  • @shikhatripathi6731
    @shikhatripathi6731 4 ปีที่แล้ว +1

    Mr.Joe u very beautifully explained the insertion sort 😊

  • @harshulgoel7977
    @harshulgoel7977 8 ปีที่แล้ว

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

  • @CarsonJamesCook
    @CarsonJamesCook 8 ปีที่แล้ว

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

  • @arpankumarlahiri4180
    @arpankumarlahiri4180 5 ปีที่แล้ว

    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)

  • @robinandrews5613
    @robinandrews5613 5 ปีที่แล้ว +3

    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.

  • @ManishKumar-zl3iv
    @ManishKumar-zl3iv 4 ปีที่แล้ว

    That while loop cleared all my doubts

  • @4vir4l
    @4vir4l 5 ปีที่แล้ว +1

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

    • @77ragnarok77
      @77ragnarok77 5 ปีที่แล้ว +2

      Yup...or it can also be done by for j in range(i,0,-1):
      And then by applying the condition a[j]

    • @neelsalunke6422
      @neelsalunke6422 5 ปีที่แล้ว +1

      Yup , got the solution from your comment, Thanks a lot macha

  • @yes4me
    @yes4me 2 ปีที่แล้ว

    There are 2 problems in this python code with the 2 for loops.
    for j in range(i - 1, 0, -1) is not valid. You are missing the first 2 numbers. It should be for j in range(i - 1, -1, -1)
    The if min_value < a_list[j]: ... else also does not work if you have only 2 numbers to swap. If you have 2 numbers, the code never enters the else and the first value is not overwritten by the min_value

  • @shanmalik92
    @shanmalik92 4 ปีที่แล้ว

    Another way of doing the same:
    def InsertionSort(Sortee):
    for index,item in enumerate(Sortee):
    if index==0:
    continue
    ti=index
    while item

  • @guccilover2009
    @guccilover2009 5 ปีที่แล้ว +1

    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]

    • @oggiai
      @oggiai  5 ปีที่แล้ว

      Thanks Sabrina. You should share your code for the whole algorithm.

    • @guccilover2009
      @guccilover2009 5 ปีที่แล้ว +2

      @@oggiai Sure. here is the whole code for the one I mentioned. If we use "A[j+1] = A[j]" under "A[j] > curNum:", it will lead to incorrect sorted list because "A[j+1] = A[j]" over-writes elements instead of swap elements
      def insertion_sort(A):
      for i in range(1, len(A)):
      curNum = A[i]
      for j in range(i-1, 0, -1):
      if A[j] > curNum:
      A[j+1], A[j] = A[j], A[j+1]
      else:
      A[j+1] = curNum
      break
      return A

    • @cloudprograms9612
      @cloudprograms9612 3 ปีที่แล้ว

      @@guccilover2009 this is still incorrect, plz run the list where A= [99,1,3,2]

    • @omreekapon2465
      @omreekapon2465 2 ปีที่แล้ว +1

      @@cloudprograms9612 yes, because again you should change>> for j in range(i-1, 0, -1): with>> for j in range(i-1, -1, -1):

  • @JorSenpai
    @JorSenpai 5 ปีที่แล้ว

    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

  • @mayank_somethin
    @mayank_somethin 6 ปีที่แล้ว +1

    Please put the code in the description so that we can directly copy paste it ;)

    • @oggiai
      @oggiai  6 ปีที่แล้ว +1

      Www.github.com/joeyajames/python

  • @pythontutorialinhindi994
    @pythontutorialinhindi994 6 ปีที่แล้ว

    tanks Joe james

  • @nathanpuritt8595
    @nathanpuritt8595 8 ปีที่แล้ว +1

    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?

    • @oggiai
      @oggiai  8 ปีที่แล้ว

      +Nathan Puritt actually, this code sorts an array. Sorry for the confusion in terminology: in Python arrays are called Lists, but they're most similar in Java to ArrayLists, which are based on Arrays. I don't have any videos on sorting Linked Lists, and I think it's pretty unusual that people try to sort Linked Lists. I also have a bunch of videos on Java sorting algorithms for arrays and arrayLists.

    • @nathanpuritt8595
      @nathanpuritt8595 8 ปีที่แล้ว

      unfortunately, I do not want to code a linked list but I am required to for my schooling. Thanks for your help.

  • @NguyenNguyen-d6j
    @NguyenNguyen-d6j ปีที่แล้ว

    how did you light up the like button at the end?

  • @宏杰李
    @宏杰李 8 ปีที่แล้ว

    thanks, those videos are very helpful!

  • @matiasO_o
    @matiasO_o 4 หลายเดือนก่อน

    what is the break keyword used for here? i know what it does but what purpose it serves here

  • @alejandroalmeida4025
    @alejandroalmeida4025 ปีที่แล้ว

    thank you for this

    • @oggiai
      @oggiai  ปีที่แล้ว

      You bet!

  • @KetanSinghvsec
    @KetanSinghvsec 8 ปีที่แล้ว +1

    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.

    • @oggiai
      @oggiai  8 ปีที่แล้ว

      +Ketan Singh the code on GitHub is always the latest code. I made a correction in line 4 in the range( ), so please use the github code.

    • @KetanSinghvsec
      @KetanSinghvsec 8 ปีที่แล้ว

      Joe James Ok thanks Joe. Any chance if you can make the corrections in the video also? Perhaps include an annotation at the start or something, so that it doesn't get confusing for new bees like me. I know editing the video might be a bit tough though.
      Oh, and just to let you know, I love your videos. They are short, precise and just make the right sense. Keep up :)

    • @oggiai
      @oggiai  8 ปีที่แล้ว

      Yeah, I already edited the video the best I could. TH-cam has very rudimentary editing features, so I think depending on your browser my edits may not even show up.

    • @KetanSinghvsec
      @KetanSinghvsec 8 ปีที่แล้ว

      Oh !! I didn't know youtube has such a behaviour as well. Yes, I do not see any changes in the video. Anyways thanks for pointing that out.

    • @evaou9557
      @evaou9557 7 ปีที่แล้ว +1

      The python code at [4:35] has a bug. To fix it, we could add the following code between line 6 and 7. "if j==0: A[j] = curNum"

  • @wajeshubham
    @wajeshubham 4 ปีที่แล้ว +4

    It should be.....for j in range(i-1,-1,-1):
    As we also want to include index 0 in j

  • @m.iqbalmaulana7328
    @m.iqbalmaulana7328 6 ปีที่แล้ว +1

    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 ???

    • @travhes
      @travhes 6 ปีที่แล้ว +1

      I think it's because j+1 is only equal to i on the first iteration of the inner for loop. On the subsequent iterations, the value of j decrements by 1.

    • @vanshgulati4808
      @vanshgulati4808 5 ปีที่แล้ว

      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)

  • @elgatoloco
    @elgatoloco 9 ปีที่แล้ว

    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.

    • @oggiai
      @oggiai  9 ปีที่แล้ว +1

      +Никола Пауновић a very common problem in python is tabs. When you look at the screen you can't tell the difference between 4 spaces and a tab, but the Python interpreter sees that as an error. Your text editor probably has an option that lets you view hidden characters, so turn that on and make sure you do not have a mixture of spaces and tabs. You must either use all tabs for indents, or always the same number of spaces for indents throughout any python program. If that doesn't solve the problem then tell me what your error message is.

    • @elgatoloco
      @elgatoloco 9 ปีที่แล้ว

      +Joe James
      Thx for the quick response. No, I don't get an error message. Problem is that the first number in the list doesn't get sorted. Here's a fiddle with code pasted from your github repo: pythonfiddle.com/insertion-sort-not-working. I've just added a return statement at the end.

    • @elgatoloco
      @elgatoloco 9 ปีที่แล้ว +1

      +Joe James Ok, I think I got it. Your inner loop seems to never get to the first element of the outer one. Although, when you insert the while loop in its place, everything's fine. Here's my code with nested for loops that I got to work:
      def insertion_sort(A):
      for i in range(1, len(A)):
      for j in range(i, 0, -1):
      if A[j] < A[j-1]:
      A[j], A[j-1] = A[j-1], A[j]
      else:
      break
      return A
      Now, with j-1 it reaches for the first element of the outer loop when doing the comparison.

    • @oggiai
      @oggiai  9 ปีที่แล้ว

      +Никола Пауновић yeah, i just made this change and it worked, for j in range(i-1, -1, -1):

    • @vanshgulati4808
      @vanshgulati4808 5 ปีที่แล้ว

      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)

  • @djjiang3718
    @djjiang3718 4 ปีที่แล้ว +1

    Joe your shift insertion sort, still not right, the lowest won't show up
    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
    return A
    A=[2,4,5,3,1,9,6]
    print(InsertionSort(A))
    # print result [1] is missing
    #[2, 2, 3, 4, 5, 6, 9]

    • @oggiai
      @oggiai  4 ปีที่แล้ว +1

      seems to work fine for me.
      Don't call the sort using print(insertion_sort1(A)). Call it like this:
      A = [5, 9, 1, 2, 4, 8, 6, 3, 7]
      print(A)
      insertion_sort1(A)
      print(A)
      A=[2,4,5,3,1,9,6]
      insertion_sort3(A)
      print(A)

    • @djjiang3718
      @djjiang3718 4 ปีที่แล้ว

      @@oggiai Thank you Joe, Yes all work now, guess something wrong from my end when I run the code, Thanks

  • @jjc9003
    @jjc9003 5 ปีที่แล้ว

    The last example of code does not work correctly.

  • @Qornv
    @Qornv 5 ปีที่แล้ว +13

    This is incorrent...

  • @Tem0inek
    @Tem0inek 9 ปีที่แล้ว

    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?

    • @oggiai
      @oggiai  9 ปีที่แล้ว +1

      +Wiktor Winczura your problem is data type. You're sorting integers as strings. If Python sees these as Integers it will sort them correctly, but if it sees them as strings then it just starts reading characters from the left as if it were alphabetizing words. So you probably need to convert your data to integers.

  • @jiashenglai5509
    @jiashenglai5509 6 ปีที่แล้ว

    thank you

  • @remusmocanu3390
    @remusmocanu3390 5 ปีที่แล้ว

    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 currentNumber):
    list[j+1] = list[j]
    else:
    list[j+1] = currentNumber
    break

  • @asmitadgaonkar8854
    @asmitadgaonkar8854 4 ปีที่แล้ว +1

    Error in "for j in range (i-1,.....)

  • @Deathvoltaje
    @Deathvoltaje 5 ปีที่แล้ว

    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.

  • @lucaslu9273
    @lucaslu9273 4 ปีที่แล้ว

    I think the shifting method may not be correct.

  • @km2052
    @km2052 8 ปีที่แล้ว

    THX

  • @dr.drakon3928
    @dr.drakon3928 7 ปีที่แล้ว

    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.

    • @Hiperultimate
      @Hiperultimate 6 ปีที่แล้ว

      You will see the difference if the list has some immense amount of values in it... Computers nowadays are fast so 10,000 or 100,000 values are not much... Try using it on a much bigger list and you will see the difference.

  • @parthsarathidixit5648
    @parthsarathidixit5648 3 ปีที่แล้ว

    a = [5,6,9,1,3,0,15]
    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
    this code is not workin its returning the same original list

  • @zaheerkhan8097
    @zaheerkhan8097 4 ปีที่แล้ว

    As python has internal timsort algorithm to sort data , do we need to write other sorting algorithms in python . What case is this used

    • @oggiai
      @oggiai  4 ปีที่แล้ว +1

      Right, Python’s built-in sorting algorithm is very fast. You may never need to write your own sorting algorithm. But sorting algorithms is a common part of every intro algorithms course, and hence are a frequent interview topic.

  • @binfu4820
    @binfu4820 5 ปีที่แล้ว +2

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

  • @akshajajay5900
    @akshajajay5900 5 ปีที่แล้ว

    wait who's joe?

  • @timli142
    @timli142 6 ปีที่แล้ว

    isnt this just bubblesort

  • @rajarshibarman4474
    @rajarshibarman4474 4 ปีที่แล้ว

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

  • @RaoWaqrAkram
    @RaoWaqrAkram 5 ปีที่แล้ว

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

    • @oggiai
      @oggiai  5 ปีที่แล้ว

      Did you retype the code yourself, or run code from my GitHub site?

  • @tomcat9761
    @tomcat9761 2 ปีที่แล้ว

    who's here because of coding interviews? lmao

  • @MissOakland510
    @MissOakland510 8 ปีที่แล้ว +1

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

  • @Wtf_Ahmad
    @Wtf_Ahmad 6 ปีที่แล้ว +1

    Swaaaaap
    😂 😂 😂
    No offence

  • @kumarabhishek29
    @kumarabhishek29 5 ปีที่แล้ว

    what will it return?? babaji ka thullu??

  • @AtulSharma-hy9yo
    @AtulSharma-hy9yo 6 ปีที่แล้ว

    Swaaaap

  • @JIMPIERCE-JP257
    @JIMPIERCE-JP257 5 หลายเดือนก่อน

    CODE IS WRONG!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  • @jyothinkjayan5442
    @jyothinkjayan5442 4 ปีที่แล้ว

    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