Featured
- Get link
- X
- Other Apps
Insertion sort in python
Here we add the element to sorted list from unsorted list. The element are not just append or swapped like selection sort. We find the appropriate position for the element then add it to the sorted list.
Algorithm:
1) keep first element as sorted list and others as unsorted list
2) Compare first and second element arrange in order
3) pick next element, compare with all elements before and arrange in order
4) repeat until last element and the list is sorted
Best time complexity: 0[n]
Average time complexity: 0[n^2]
Worst time complexity: 0[n^2]
Working process of selection sort:
Take list [61, 3, 43, 25, 16, 34].
Iteration 1:
take 61 as sorted list and others as unsorted
take next element 3 and compare with sorted list
3<61 so swap(the num will be temp placed not fully swapped)
Iteration 2: [3, 61, 43, 25, 16, 34]
take 43 and compare with sorted list. Always move from right to left.
43<3 no so it is placed in postion 1
Iteration 3: [3, 43, 61, 25, 16, 34]
take 25 and compare with sorted list.
25<43 so swap
25<3 no so it is placed in postion 1
Iteration 3: [3, 25, 43, 61, 16, 34]
take 16 and compare with sorted list.
16<43 so swap
16<25 so swap
16<3 no so the 16 is placed in postion 1
Iteration 4: [3, 16, 25, 43, 61, 34]
take 34 and compare with sorted list.
34<43 so swap
34<25 no
34<16 no
3<16 no
so the element is placed before 43 in position 3
[3, 16, 25, 34, 43, 61]
Code for Insertion sort :
Output :
Hope you understand the program and try yourself for more clear view feel free to comment your thoughts!!
- Get link
- X
- Other Apps

Comments
Post a Comment