Insertion Sort In Python Explained (With Example And Code)

Поділитися
Вставка
  • Опубліковано 29 гру 2024

КОМЕНТАРІ • 134

  • @Sussy_Neko
    @Sussy_Neko 3 роки тому +80

    Absolutely beautiful ,a simple and concise explanation ,Wish I had teachers like you.

  • @troyke
    @troyke Рік тому +16

    OMG! I've only watched a few mins of your video and I can't believe what a great job you did on the explanation and the beauty, pace, and clarity of the presentation! Top-notch! You really need to continue being a Tech Trainer either FT or on the side, as you are VERY GOOD at it!

  • @deshawnbattle7510
    @deshawnbattle7510 2 роки тому +5

    I’m reading a book for school and the problem had 2x as much code wayyyyy harder than it had to be… thanks man!!

  • @heyitsKim1912
    @heyitsKim1912 Рік тому +1

    I found this coding example is the easiest yet most efficient one out there! Thank you Felix!

  • @saralee548
    @saralee548 2 роки тому +5

    ive been using your channel to study for coding interviews, most simple explanations out there, ty!

  • @Jonzy6ixx
    @Jonzy6ixx 9 місяців тому

    ❤❤❤❤ the simplest video have seen so far that made this so simple. I have watched dozens of videos at a point I said I will never use insertions sort 😅

  • @icchigoat
    @icchigoat 3 роки тому +3

    I LOVE YOU SO MUCH MAN YOU'RE A LIFESAVER WISH ME LUCK I HAVE AN EXAM ON TUESDAY

  • @tejaswini07j
    @tejaswini07j Рік тому

    I have been running away from this Sorting and Searching since 2011(Pre University Years), I am in the 6th year of my career and TIL "SORTING", which is simple and non-scary.
    Thank you!

  • @nishantmehra7031
    @nishantmehra7031 3 роки тому +6

    You made this look so easy dude ... thanks a lot

  • @cigxhang486
    @cigxhang486 2 роки тому

    only till I watched this video did I know that there are two loops, one to the right and one to the left. Thank you for saving my life

  • @glockncheese
    @glockncheese 3 роки тому +2

    This is literally a lifesaver. Thank u.

  • @WriterRomanSavin
    @WriterRomanSavin Рік тому +1

    A perfect explanation and elegant coding solution

  • @starlight_garden
    @starlight_garden Рік тому +4

    Timestamps/suggested chapters:
    0:00 Intro
    0:08 Overview
    0:31 Example
    3:21 Code
    7:44 Outro

  • @dkadayinthailand3082
    @dkadayinthailand3082 Рік тому +26

    Is there any reason you would want to use this instead of the built in sort function in Python?

    • @nosi851
      @nosi851 11 місяців тому +24

      my stupid ass teacher wants us to think of solutions instead

    • @elemeismo7810
      @elemeismo7810 10 місяців тому +8

      Job interviews

    • @Jonzy6ixx
      @Jonzy6ixx 9 місяців тому +1

      I was about to ask the same

    • @darcash1738
      @darcash1738 9 місяців тому +1

      Timsort op. Look into its implementation, that’s why it’s built in. Done v intelligently

    • @elestroaryan2501
      @elestroaryan2501 9 місяців тому +1

      In Java we have function but in interview the ask us to make by ourself

  • @jimmadjy
    @jimmadjy 10 місяців тому

    Thank you man . Best explanation , easy to understand

  • @jonassteinberg3779
    @jonassteinberg3779 9 місяців тому +1

    aside from readability, which in this case I don't think is a win, you don't need to even define j because if you think about it j is just i, so the code could be written as:
    def iterative_insertion_sort(arr: list):
    for i in range(1, len(arr)):
    while arr[i-1] > arr[i] and i > 0:
    arr[i-1], arr[i] = arr[i], arr[i-1]
    i -= 1
    This code block passes all my unit tests of which I have 14. I'll list them below. One thing Felix does which I haven't seen anyone else do is instead of comparing right to left he actually compares left to right. I guess it doesn't matter. My mind makes easier send of things as right to left, especially since you're counting down *to the left* in terms of comparisons. Anyway...no need for j.
    from iterative_insertion_sort import iterative_insertion_sort
    import pytest
    def test_alternating_zeroes_and_ones():
    arr = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
    assert iterative_insertion_sort(arr) == sorted(arr)
    def test_increasing_decreasing():
    arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
    assert iterative_insertion_sort(arr) == sorted(arr)
    def test_decreasing_increasing():
    arr = [19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + list(range(1, 20))
    assert iterative_insertion_sort(arr) == sorted(arr)
    def test_all_but_one_element_the_same():
    arr = [0] * 19 + [1]
    assert iterative_insertion_sort(arr) == sorted(arr)
    def test_all_but_one_element_the_same_big_delta():
    arr = [1] * 19 + [100]
    assert iterative_insertion_sort(arr) == sorted(arr)
    def test_large_range():
    arr = [-100] + list(range(1, 20))
    assert iterative_insertion_sort(arr) == sorted(arr)
    def test_very_close_numbers():
    arr = [i/10 for i in range(20)]
    assert iterative_insertion_sort(arr) == sorted(arr)
    def test_all_negative_numbers():
    arr = list(range(0, -5, -1))
    assert iterative_insertion_sort(arr) == sorted(arr)
    def test_mix_of_positive_and_negative():
    arr = [-10, 10] * 10
    assert iterative_insertion_sort(arr) == sorted(arr)
    def test_alternating_high_and_low():
    arr = [20 - i if i % 2 == 0 else i for i in range(20)]
    assert iterative_insertion_sort(arr) == sorted(arr)
    def test_peak_in_the_middle():
    arr = [2] * 10 + [3] + [2] * 9
    assert iterative_insertion_sort(arr) == sorted(arr)
    def test_small_range_random_integers():
    arr = [5, 3, 0, 4, 0, 4, 4, 0, 4, 0, 0, 0, 0, 4, 1, 0, 1, 4, 3, 5]
    assert iterative_insertion_sort(arr) == sorted(arr)
    def test_floating_point_numbers():
    arr = [float(i) for i in range(20)]
    assert iterative_insertion_sort(arr) == sorted(arr)
    def test_large_value_at_the_beginning():
    arr = [1000] + list(range(1, 20))
    assert iterative_insertion_sort(arr) == sorted(arr)

  • @rajrish
    @rajrish 8 місяців тому +2

    I found your code simple but but i dont think it is the correct example of insertion sort. bcz in insertion sort, we pick one element and put it to its correct location, but you kept swapping the element with the previous element until the previous element is not smaller than our main element. So it is technically an example of bubble sort that is executed in the reverse direction. You won't get what im trying to say just by reading my sentence. Therefore look at this example of insertion sort :
    l1 = [5,1,3,4,2]
    n = len(l1)
    for i in range(n):
    k = l1[i]
    j = i-1
    while k=0 :
    l1[j+1] = l1[j]
    j -= 1
    else:
    l1[j+1] = k
    print('Sorted list: ', l1)

  • @lena-ck9wz
    @lena-ck9wz 4 роки тому +10

    thank you for explaining this in a simple way 🙏🏼

  • @jiaziliang5143
    @jiaziliang5143 3 роки тому +2

    Very clear explanation, thank you so much!

  • @olafschlammbeutel
    @olafschlammbeutel 4 роки тому +3

    Really nice and clean code! Good work!

  • @jorgeluismadridgomez1643
    @jorgeluismadridgomez1643 2 роки тому +2

    I was told that in insertion sort we don't make a swap and we only move the elements greater than the current to the right next position until we reach the current correct position. Does that explanation make sense? or the swap action is the same that the shift action?

    • @sahilshukla8619
      @sahilshukla8619 2 роки тому +2

      Left shifting a digit one by one is equivalent to swapping the digit on left hand side one by one

  • @kiranvarghese6046
    @kiranvarghese6046 2 роки тому +2

    thanks a lot for this simple code man .......a lot of sites on the internet had to many complicated codes but this one was small and simple :)

  • @SylDragonia
    @SylDragonia Місяць тому

    7:20 just to correct you. There is a -1 index in Python but it points to the last element.

  • @OmUplenchwar
    @OmUplenchwar 3 місяці тому

    just amazing man. keep it up!

  • @sambhavbhalla2697
    @sambhavbhalla2697 3 роки тому +2

    Hey , I had a doubt cuz when I wrote this code it was showing list index out of range also why did we do j=-1 , if we are going from left to right so we are increasing the index we aren't going from right to left?

    • @prashantpareek5863
      @prashantpareek5863 3 роки тому +18

      the reason why j = j -1 is used is probably because,in this algo the elements to the left are always sorted before we move further(towards right),for example
      li = [2,6,5,1,3,4]
      here we start the for loop from index 1 i.e from the number '6' and check if the number to the left of '6' is greater than 6,if it is we swap and since 2 is not greater than 6, we do not swap, and since, we do not swap j = j-1 doesn't get triggered in the loop ,now we move further and now j = 2 (since, j = i),we check if the number '6' is greater than the next number, which is '5',since it is,we enter the for loop and swap these two, now as we know j is equal to 2,and we need to check if the number we just swapped is also greater than the number which is left of this newly swapped number, so, we are checking if the number '5' which just now came in the place of '6', is also greater than the number '2',to check this we decrement j by one and since it is decremented, now, j again checks if the number to the left is smaller than the number present at j, since, '5' is greater than '2', no swapping takes place. But as we move, j is equal to 3,and we check if the number to the left of '1', is greater than '1' (mind you,now the li looks like this li = [2,5,6,1,3,4])
      since '6' is greater than '1', we swap now the array looks like this li = [2,5,1,6,3,4],as i had told you in the beginning that this algo always has the elemente in the left soretd before it moves forward,but you can see that the array to the left of 3 is not sorted,coz '1' is in the middle when it should be at the beginning, so, we decrease j to 2 again and check if the number to the left of '1' is greater than '1' since,5 is greater than '1' we swap since a swap has happened we further decrease j to 1 and check if the number to the left of '1' is greater than '1' since '2' is greater we swap and we get li = [1,2,5,6,3,4], now we move further in the same way.

    • @thomasjefferson6225
      @thomasjefferson6225 3 роки тому +2

      @@prashantpareek5863 this should have more likes. basically j is an index used to know how many comparisions needs to be done for each key.

  • @SuperBhavanishankar
    @SuperBhavanishankar 3 роки тому +2

    Hi. can this even more simpler version works? -->
    for i in range(0,len(lst)):
    while (lst[i-1]>lst[i] and i>0):
    lst[i-1],lst[i]=lst[i],lst[i-1]
    i-=1
    print(lst)

    • @nvrbck
      @nvrbck 2 роки тому +2

      he defined a function and you didnt

  • @NawbieOSRS
    @NawbieOSRS Місяць тому

    is "j = i" actually making a new array? Or just defining the value in "I"?

  • @yeleukenov
    @yeleukenov 6 місяців тому

    Eloquent, beautiful. Thanks

  • @johnmahugu
    @johnmahugu 5 місяців тому +1

    brilliant!!!

  • @ryanboll9464
    @ryanboll9464 Рік тому

    New to coding. Curious why you used i in your for loop and then set j to i instead of just using j to iterate through?

  • @toshans845
    @toshans845 Рік тому

    please make more videos like this for more concepts like Job scheduling with Greedy method , Knapsack problems, Travelling salesman Problems etc , it will be very useful for many tech enthusiasts 🙏🏻

  • @TheKorkahn
    @TheKorkahn 4 роки тому +6

    Very nice, just what I needed, thanks!

  • @abianand949
    @abianand949 2 роки тому

    very Informative and simple.. Loved your explanation..

  • @NadiraRupasinghe
    @NadiraRupasinghe 2 місяці тому

    I would really appreciate if you can use appropriate and understandable identifiers for variables.

  • @bhavishahadiyal7836
    @bhavishahadiyal7836 3 роки тому +3

    Thankyou it's really great keep it up:)

  • @challasomesh2397
    @challasomesh2397 2 роки тому

    Perfect explanation, Thank you sir!

  • @g__red
    @g__red Рік тому

    very good explanation and very understandable code!

  • @NOM855
    @NOM855 Рік тому

    i have a question
    why u'v used while instead we can use for like that :
    def tri_insertion(L):
    for i in range(1,len(l)):
    for j in range(len(l[:i])):
    if l[i]

  • @chasest.claire9853
    @chasest.claire9853 Рік тому

    why would you call a for loop, which is slower iirc, instead of maybe append value to list then just call the sort on the array? I’m still learning efficiency

  • @RamRam-jp2kc
    @RamRam-jp2kc 2 роки тому

    best video on youtube.

  • @badboy333666999
    @badboy333666999 2 роки тому

    Brilliant explanation. Thank you!

  • @shahriarshovo3382
    @shahriarshovo3382 3 роки тому +1

    may you explain more about j=j-1 ? should it decreasing from last element ?

    • @prashantpareek5863
      @prashantpareek5863 3 роки тому +8

      the reason why j = j -1 is used is probably because,in this algo the elements to the left are always sorted before we move further(towards right),for example
      li = [2,6,5,1,3,4]
      here we start the for loop from index 1 i.e from the number '6' and check if the number to the left of '6' is greater than 6,if it is we swap and since 2 is not greater than 6, we do not swap, and since, we do not swap j = j-1 doesn't get triggered in the loop ,now we move further and now j = 2 (since, j = i),we check if the number '6' is greater than the next number, which is '5',since it is,we enter the for loop and swap these two, now as we know j is equal to 2,and we need to check if the number we just swapped is also greater than the number which is left of this newly swapped number, so, we are checking if the number '5' which just now came in the place of '6', is also greater than the number '2',to check this we decrement j by one and since it is decremented, now, j again checks if the number to the left is smaller than the number present at j, since, '5' is greater than '2', no swapping takes place. But as we move, j is equal to 3,and we check if the number to the left of '1', is greater than '1' (mind you,now the li looks like this li = [2,5,6,1,3,4])
      since '6' is greater than '1', we swap now the array looks like this li = [2,5,1,6,3,4],as i had told you in the beginning that this algo always has the elemente in the left soretd before it moves forward,but you can see that the array to the left of 3 is not sorted,coz '1' is in the middle when it should be at the beginning, so, we decrease j to 2 again and check if the number to the left of '1' is greater than '1' since,5 is greater than '1' we swap since a swap has happened we further decrease j to 1 and check if the number to the left of '1' is greater than '1' since '2' is greater we swap and we get li = [1,2,5,6,3,4], now we move further in the same way.

    • @shahriarshovo3382
      @shahriarshovo3382 3 роки тому +2

      @@prashantpareek5863 Thank you so much ❤️

    • @prashantpareek5863
      @prashantpareek5863 3 роки тому +1

      @@shahriarshovo3382 I hope the doubt was cleared.. 👍

    • @shahriarshovo3382
      @shahriarshovo3382 3 роки тому +1

      @@prashantpareek5863 yes . :D

    • @prashantpareek5863
      @prashantpareek5863 3 роки тому

      @@shahriarshovo3382 hey, Hi, are you Shariar from Dennis Ivy's course? The guy who did the front end of the Devsearch project?

  • @Nickgaming19
    @Nickgaming19 Рік тому

    Thanks brother, This helped me a lot

  • @jimo1150
    @jimo1150 4 місяці тому +1

    what is the point of j = i ? and not just use i

  • @zzgladiatorzz252
    @zzgladiatorzz252 13 днів тому

    I know I'm seeing this video a bit late but... I wanted to ask if this same code will be acceptable in
    exams like Cambridge Computer Science (9618)

  • @Abhi-fq4wc
    @Abhi-fq4wc 27 днів тому

    Please make complete dsa playlist in python

  • @pedramghasemi1417
    @pedramghasemi1417 5 місяців тому

    Thank you so much, im grateful

  • @holmbrg-_-2221
    @holmbrg-_-2221 9 місяців тому

    Why do you need to define a new variable j? You can just ignore j and use i. Am i wrong?

  • @mohankarthik9619
    @mohankarthik9619 2 роки тому

    Can you explain the condition used in program

  • @devansh6839
    @devansh6839 Рік тому

    a good explanation!

  • @plusinfinity3251
    @plusinfinity3251 3 роки тому

    Good explanation 👏👍

  • @StoryBot1167
    @StoryBot1167 10 місяців тому

    superb master

  • @atkbane
    @atkbane Рік тому

    muy buena explicacion, gracias por el video

  • @peachfreude
    @peachfreude 3 роки тому

    how to print number 1,2,3,4,5 in ascending then descending order in a same line? the output should be 1,2,3,4,5,4,3,2,1. can you help?

    • @Game-nr3sr
      @Game-nr3sr 2 роки тому +1

      do reverse list and then join this from 1::

  • @DimaCleann
    @DimaCleann 9 місяців тому

    why did we check if j is greater than zero ? we start the loop from zero

  • @mariusbaldovin4959
    @mariusbaldovin4959 8 місяців тому

    There is actually an item at index -1 and it is the last element from the list

  • @hadrian2801
    @hadrian2801 2 роки тому

    Why does j need to be used, cant i just be used instead?

  • @Phlypour
    @Phlypour Рік тому

    All is fine, but I'm not sure why did you create a 'j' that is 'i'? I removed the 'j' variable and the result is just the same. Is it due to some common or PEP practices or a different Python version?

    • @g__red
      @g__red Рік тому

      I think that if you do not write "j = i" what happens is that the while loop starts from the beginning of the list each time (it goes to the right and then to the left for each iteration) so it's less efficient, whereas with "j = i" it starts at "i" position and goes backwards thanks to "j -= 1".

    • @lentlen5857
      @lentlen5857 Рік тому

      this algorithm is not insertion sort algo ...
      this IS an Insertion sort :
      def insertion(d):
      for i in range(1,len(d)):
      key = d[i]
      j = i-1
      while j >= 0 and key

    • @lentlen5857
      @lentlen5857 Рік тому

      I mean the algorithm in the video is NOT an insertion sort algorithm

  • @devendravyas328
    @devendravyas328 6 місяців тому

    Be continue bro.

  • @mountainp800
    @mountainp800 2 роки тому

    How does this have better presentation than my online university?

  • @arhamatif2943
    @arhamatif2943 Рік тому

    hey can u give the code so i can copy and paste cause mine's not working

  • @bmk2561
    @bmk2561 Рік тому

    can someone explain whats j=i used for

  • @PrajithPS-oj4rj
    @PrajithPS-oj4rj 9 місяців тому

    thanks a lot brother!

  • @clumsySenpai
    @clumsySenpai 2 роки тому +1

    I trust you and your console.

  • @burnertrump875
    @burnertrump875 3 роки тому

    Does this work with numbers larger than 9?

  • @isit4768
    @isit4768 4 місяці тому +1

    Everything else is clear but why did he used "j" instead of "i" ???

  • @christianrodier3381
    @christianrodier3381 4 місяці тому

    super helpful

  • @rudripancholifc
    @rudripancholifc 2 роки тому

    Love from prayagraj

  • @diyafathimadiyafathima.k5494
    @diyafathimadiyafathima.k5494 Рік тому +1

    Can anyone explain why we put the j-=1?

    • @strade740
      @strade740 11 місяців тому

      j -= 1 means j = j - 1 it is done so that we keep on comparing the value with the left value until the while loop condition become wrong
      too late haha, but i hope u have already figured it out!

  • @33krishh
    @33krishh Рік тому +1

    i caN Trust you now sir

  • @guilhermebarnes7663
    @guilhermebarnes7663 2 роки тому +1

    This seems like an inefficient bubble sort algo

  • @ignitedminds6164
    @ignitedminds6164 10 місяців тому

    Sir continue the series in leetcode

  • @KashishYadav657
    @KashishYadav657 10 місяців тому +1

    Not showing the output

  • @pianocoversjulian1008
    @pianocoversjulian1008 3 роки тому

    Better and shorter than the one of my teacher 👌😅

  • @baby_doll4.13
    @baby_doll4.13 3 роки тому

    insertion sort perform shift operations rather than swap.

  • @lebu8769
    @lebu8769 3 роки тому +1

    I didn't knew that Felix had started a programming channel apart from his PEWDIEPIE channel.
    But my doubt, is why is he having so less SUBSCRIBERS.........
    😂

  • @saeid4349
    @saeid4349 2 місяці тому

    You forgot to say that running-time in best case of Insertion sort is TETA(N)

  • @cr1064
    @cr1064 Рік тому

    Thank you!!

  • @DanielSmith-uj7rr
    @DanielSmith-uj7rr 3 роки тому

    Thank you! Thank you! Thank you!

  • @cheerslove9975
    @cheerslove9975 2 роки тому

    Thank you man

  • @oneloveafrica8860
    @oneloveafrica8860 Рік тому

    wow it working🥳

  • @idklife7381
    @idklife7381 3 місяці тому

    THANK YOU

  • @factaboutindia7243
    @factaboutindia7243 Рік тому +1

    this code is not worked

  • @x0fficial
    @x0fficial Рік тому

    Super good!

  • @kanikapanwar7305
    @kanikapanwar7305 2 роки тому

    Thank u

  • @helpapproved
    @helpapproved 3 роки тому

    tq bro .

  • @marwasolh9449
    @marwasolh9449 Рік тому

    ❤❤❤❤❤

  • @mohamedshiraf2855
    @mohamedshiraf2855 2 роки тому

    Thanks

  • @julianavarela4936
    @julianavarela4936 3 місяці тому

    A hero

  • @lakshyadhiman2061
    @lakshyadhiman2061 2 роки тому

    😎🤝

  • @awetinoawets9290
    @awetinoawets9290 4 місяці тому

    You forgot return arr[::-1]

    • @kofiboahen2156
      @kofiboahen2156 2 місяці тому

      return arr at the end of the function

  • @Lumiobyte
    @Lumiobyte 4 місяці тому

    LinusTechTips

  • @jacobsola3521
    @jacobsola3521 Рік тому

    Noice.

  • @cleverarsey3568
    @cleverarsey3568 Рік тому +1

    if anyone else is here cuz of faris foo like this comment

  • @crazypage2621
    @crazypage2621 4 місяці тому +1

    bro your code is not correct at all thank you

  • @dhruvakanumolu8997
    @dhruvakanumolu8997 2 місяці тому

    Bro the code is wrong 😂

  • @sanooosai
    @sanooosai 8 місяців тому +1

    thank you

  • @Debashis-n3m
    @Debashis-n3m 10 місяців тому

    Thanks