The array is virtually split into a sorted and an unsorted part. Values from the unsorted part is picked and placed at the correct position in the sorted part.
Complexity:-
Worst-case and average-case:- O(n2 )
best case:- O(n)
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class InsertionSort{ public static void main(String []args){ int[] arr = { 3, 5, 1, 6, 2, 4 }; for(int i=1; i<arr.length; i++){ int temp = arr[i]; int j = i - 1; while(j>=0 && arr[j]>temp){ arr[j+1] = arr[j]; j--; } arr[j+1] = temp; } for(int x:arr) System.out.print(x+" "); } } |
Python
def insertion_sort(array): for slot in range(1, len(array)): value = array[slot] test_slot = slot - 1 while test_slot > -1 and array[test_slot] > value: array[test_slot + 1] = array[test_slot] test_slot = test_slot - 1 array[test_slot + 1] = value return array array = [3, 5, 1, 6, 2, 4] print(insertion_sort(array)) |
Pseudocode:-(Another approach)
i ← 1
while i < length(A)
j ← i
while j > 0 and A[j-1] > A[j]
swap A[j] and A[j-1]
j ← j - 1
end while
i ← i + 1
end while