Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.
However, insertion sort provides several advantages:
1. Simple implementation: Jon Bentley shows a three-line c version, and a five-line optimized version
Efficient for (quite) small data sets, much like other quadratic sorting algorithmsAdaptive, i.e., efficient for data sets that are already substantially sorted: the time complexity is O(kn) when each component in the input is no more than K places away from its sorted position
2. Stable; i.e., makes not change the relative order of components with equal keys
package Sorts;
import static Sorts.SortUtils.less;
import static Sorts.SortUtils.print;
/**
* @author Varun Upadhyay (https://github.com/varunu28)
* @author Podshivalov Nikita (https://github.com/nikitap492)
*/
class InsertionSort implements SortAlgorithm {
/**
* This method implements the Generic Insertion Sort
* Sorts the array in increasing order
*
* @param array The array to be sorted
**/
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
for (int j = 1; j < array.length; j++) {
// Picking up the key(Card)
T key = array[j];
int i = j - 1;
while (i >= 0 && less(key, array[i])) {
array[i + 1] = array[i];
i--;
}
// Placing the key (Card) at its correct position in the sorted subarray
array[i + 1] = key;
}
return array;
}
// Driver Program
public static void main(String[] args) {
// Integer Input
Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12};
InsertionSort sort = new InsertionSort();
sort.sort(integers);
// Output => 1 4 6 9 12 23 54 78 231
print(integers);
// String Input
String[] strings = {"c", "a", "e", "b", "d"};
sort.sort(strings);
//Output => a b c d e
print(strings);
}
}