Insertion Sort Algorithm in Python

[1326 views]


In this article, you will find a simple Insertion Sort algorithm in Python.

What is Insertion Sort?

Refer this article for full definition and Algorithm on Insertion SortAlgorithm and Pseudocode for Insertion Sort

Insertion Sort Algorithm in Python

Problem Statements:

Write an Insertion Sort program in Python.

OR

Program for Insertion Sort Algorithm in Python.

Code:

def insertionsort(alist): for each in range(1,len(alist)): current_value = alist[each] position = each while position > 0 and alist[position-1] > current_value: alist[position] = alist[position-1] position = position - 1 alist[position] = current_value return alist if __name__ == '__main__': num = int(raw_input("Enter total numbers which you are going to entered ")) nlist = [] while num > 0: no = raw_input("Enter the number") nlist.append(no) num = num - 1 result = insertionsort(nlist) print result

Output:

Enter total numbers which you are going to entered 5 Enter the number8 Enter the number5 Enter the number1 Enter the number3 Enter the number7 ['1', '3', '5', '7', '8']
        

Struggling to Understand Algorithm and Flowchart? Try our Notes



Want to Test Your Knowledge on Algorithm and Flowchart?


Other Notes you might be Interested in:




Comments



Search
Recommended Deals End in

Top Java Interview Questions PDF Guide with 30+ Pages



Online Games
Play 2048 Game Online and Relax.
Play 2048 Game Online

Quiz to Test Your Skills
Search Tags