Insertion Sort
Output: The list sorted in ascending order.
Steps:
-
Start the process.
-
Read the list of elements.
-
Begin from the second element in the list.
-
Pick the current element and store it in a temporary variable.
-
Compare the temporary value with the elements before it.
-
Shift each element one position to the right if it is greater than the temporary value.
-
Place the temporary value in its correct sorted position.
-
Move to the next element and repeat the process until the entire list is sorted.
-
Display the sorted list.
-
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