Insertion sort


Insertion Sort


Algorithm: Insertion Sort

Input: A list of elements.

Output: The list sorted in ascending order.

Steps:

  1. Start the process.

  2. Read the list of elements.

  3. Begin from the second element in the list.

  4. Pick the current element and store it in a temporary variable.

  5. Compare the temporary value with the elements before it.

  6. Shift each element one position to the right if it is greater than the temporary value.

  7. Place the temporary value in its correct sorted position.

  8. Move to the next element and repeat the process until the entire list is sorted.

  9. Display the sorted list.

  10. End the process.



# Insertion Sort


def InsertionSort(L):

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

tmp = L[i]

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

if(tmp>L[j-1]):

break

L[j] = L[j-1]

L[j] = tmp

print(L)


L = eval(input("Enter list of elements : "))

InsertionSort(L)


"""

Sample output

>python InsertionSort.py

Enter list of elements : [34,8,64,51,32,21]

[8, 21, 32, 34, 51, 64]

"""

No comments:

Post a Comment

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

Anu