Insertion sort
Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part.
Codes
public class Study {
/**
* main function to sort array using insertion sort
*
* @param args
*/
public static void main(String[] args) {
int[] arr = {1, -10, -2, 3, 8, 100, -100, 2, 6, 25};
print(arr);
System.out.println();
insertionAsc(arr);
// insertionDes(arr);
print(arr);
}
/**
* ascending order
*
* @param arr
*/
private static void insertionAsc(int[] arr) {
/*
firstUnsortedIndex means the first index of the unsorted array, the original value is 1
since we will insert from index = 1 to arr.length - 1
*/
for (int firstUnsortedIndex = 1; firstUnsortedIndex < arr.length; firstUnsortedIndex++) {
int value = arr[firstUnsortedIndex];
int i;
// insert value into index = 0 to firstUnsortedIndex
for (i = firstUnsortedIndex; i > 0 && arr[i - 1] > value; i--) {
arr[i] = arr[i - 1]; // move arr[i-1] to arr[i] position
}
arr[i] = value; // insert value into i index
}
}
/**
* descending order
*
* @param arr
*/
private static void insertionDes(int[] arr) {
for (int firstUnsortedIndex = 1; firstUnsortedIndex < arr.length; firstUnsortedIndex++) {
int value = arr[firstUnsortedIndex];
int i;
for (i = firstUnsortedIndex; i > 0 && arr[i - 1] < value; i--) {
arr[i] = arr[i - 1];
}
arr[i] = value;
}
}
/**
* swap values
*
* @param arr
* @param i
* @param j
*/
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/**
* print the array
*
* @param arr
*/
private static void print(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print("arr[" + i + "] = " + arr[i] + " ");
}
}
}