๐งฉ Insertion Sort
This page provides introduction to Insertion Sort.
Overviewโ
Insertion Sort builds the final sorted array one element at a time. It picks each element from the unsorted portion and places it in its correct position in the sorted portion by shifting larger elements to the right.
Let's sort array below, with insertion sort:
Step 1โ
Pick an element from unsorted portion of an array.
Place it in correct position in sorted array.
Step 2โ
Pick an element from unsorted portion of an array.
Place it in correct position in sorted array.
Step 3โ
Pick an element from unsorted portion of an array.
Place it in correct position in sorted array.
Step 4โ
Pick an element from unsorted portion of an array.
Place it in correct position in sorted array.
- Java
public void insertionSort(int[] arr) {
for(int i = 1; i < arr.length; i++) {
int key = arr[i];
int j = i - 1;
while(j >= 0 && key < arr[j]) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
Complexityโ
Let's say there are elements in an array.
Time Complexityโ
We are inserting an element from unsorted array into sorted array which takes , so total time complexity will be:
Space Complexityโ
Algorithm uses constant space.