JavaAlgorithms/Sorts/InsertionSort.java

56 lines
1.2 KiB
Java
Raw Normal View History

2018-11-14 01:15:47 +08:00
package Sorts;
2018-11-14 01:15:47 +08:00
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 {
2020-10-24 18:23:28 +08:00
/**
* 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;
}
2020-10-24 18:23:28 +08:00
return array;
}
2020-10-24 18:23:28 +08:00
// Driver Program
public static void main(String[] args) {
// Integer Input
Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12};
2020-10-24 18:23:28 +08:00
InsertionSort sort = new InsertionSort();
2020-10-24 18:23:28 +08:00
sort.sort(integers);
2020-10-24 18:23:28 +08:00
// Output => 1 4 6 9 12 23 54 78 231
print(integers);
2020-10-24 18:23:28 +08:00
// String Input
String[] strings = {"c", "a", "e", "b", "d"};
2020-10-24 18:23:28 +08:00
sort.sort(strings);
2020-10-24 18:23:28 +08:00
// Output => a b c d e
print(strings);
}
}