Java data structures and algorithm examples: Insertion Sort
- 2020-04-01 03:56:45
- OfStack
package al;
public class InsertionSort {
public static void main(String[] args) {
InsertionSort insertSort = new InsertionSort();
int[] elements = { 14, 77, 21, 9, 10, 50, 43, 14 };
// sort the array
insertSort.sort(elements);
// print the sorted array
for (int i = 0; i < elements.length; i++) {
System.out.print(elements[i]);
System.out.print(" ");
}
}
public void sort(int[] array) {
// min to save the minimum element for each round
int key; // save current element
for(int i=0; i<array.length; i++) {
int j = i; // current position
key = array[j];
// compare current element
while(j > 0 && array[j-1] > key) {
array[j] = array[j-1]; //shift it
j--;
}
array[j] = key;
}
}
}