Insertion Sort
public class InsertionSort {
public static void main(String[] args) {
int[] a = {15, 100, 56, 16, 7, 42, 99, 33}; //a is the array which is to be sorted
Sort(a);
}
public static void Sort(int array[]) {
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j - 1;
while ((i > -1) && (array[i] > key)) { /* This is for ascending order sorting.
For descending order,replace array[i]>key by array[i]<key*/
array[i + 1] = array[i];
i--;
}
array[i + 1] = key;
}
displayResult(array);
}
private static void displayResult(int[] input) {
System.out.println("Sorted array is :");
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + ", ");
}
System.out.println("
");
}
}
Output:
Sorted array is:
7, 15, 16, 33, 42, 56, 99, 100,