Sorting - Insertion sort

# Insertion sort

# Read elements and create list
no_of_terms = int(input("Enter number of terms : "))
List1 = []

for idx in range(0, no_of_terms, 1):
    ele = int(input("Enter element : "))
    List1.append(ele)

print("Original list :", List1)

for idx in range(1, len(List1), 1):
    while( idx>0 and List1[idx-1]>List1[idx] ):
        List1[idx],List1[idx-1] = List1[idx-1],List1[idx]
        idx = idx-1
       
print("Sorted List :", List1)


2 comments:

  1. while( idx>0 and List1[idx-1]>List1[idx] ):
    List1[idx],List1[idx-1] = List1[idx-1],List1[idx]
    idx = idx-1

    Mam i can't understand this loop.

    ReplyDelete
  2. for loop - starting from second element in list search till last
    while loop - compare first element with 0th element - that is compare current element with previous element - if current is lower swap the elements (List1[idx],List1[idx-1] = List1[idx-1],List1[idx]) and compare this element with previous, repeat this comparison untill 0th position(idx>0) or element is bigger than previous
    basically the while loop will move every element to previous position untill it is sorted to correct position.

    5 3 1 4 2
    1. for - 5 while - idx 0 does not enter while loop
    2. for - 3 while - idx 1 5>3 enter loop swap 5 and 3 (3 5 1 4 2) decrement idx to 0. while loop breaks
    3. for - 1 while - idx 2 5>1 enter loop swap 1 and 5 (3 1 5 4 2)
    decrement idx to 1 - 3>1 enter while loop swap 1 and 3 (1 3 5 4 2) decrement idx to 0. while loop breaks
    4 for 4 while idx - 3 5>4 enter loop swap 5 and 4 (1 3 4 5 2). decrement idx 2. 3>4 condition false. while loop breaks. that is 4 is in correct sorted position

    when entering while loop note all previous elements are in sorted order. move smaller element one step forward until it reaches its position or if its the smallest element it will go to the beginning....

    ReplyDelete

Don't be a silent reader...
Leave your comments...

Anu