Insertion sort: Quick look
Table of contents
The given array is divided in 2 sub parts i.e. a sorted array and an unsorted array. now, for every element in unsorted array iteration is run and a position is find for in in sorted array.
It is in-place sorting.
It is most efficient for small data sets and the data sets which are already partially sorted.
Implementation :
class InsertionSort {
public static void main(String[] args){
int[] arr = new int[]{64, 97, 32, 8, 56, 48, 0};
insertionSort(arr);
}
static void insertionSort(int[] arr){
for(int i=0; i<arr.length; i++){
int temp = arr[i];
int j = i-1;
for(; j>=0; j--){
if(arr[j]>temp){
arr[j+1] = arr[j];
}
else{
break;
}
}
arr[j+1] = temp;
}
System.out.println(Arrays.toString(arr));
}
}
Resources:
GFG Article Insertion Sort Algorithm | C++ / Java Complete explanation for Beginners and Code | DSAOne Course 18