forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSort.java
More file actions
91 lines (81 loc) · 2.95 KB
/
InsertionSort.java
File metadata and controls
91 lines (81 loc) · 2.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package com.thealgorithms.sorts;
class InsertionSort implements SortAlgorithm {
/**
* Sorts the given array using the standard Insertion Sort algorithm.
*
* @param array The array to be sorted
* @param <T> The type of elements in the array, which must be comparable
* @return The sorted array
*/
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
return sort(array, 0, array.length);
}
/**
* Sorts a subarray of the given array using the standard Insertion Sort algorithm.
*
* @param array The array to be sorted
* @param lo The starting index of the subarray
* @param hi The ending index of the subarray (exclusive)
* @param <T> The type of elements in the array, which must be comparable
* @return The sorted array
*/
public <T extends Comparable<T>> T[] sort(T[] array, final int lo, final int hi) {
if (array == null || lo >= hi) {
return array;
}
for (int i = lo + 1; i < hi; i++) {
final T key = array[i];
int j = i - 1;
while (j >= lo && SortUtils.less(key, array[j])) {
array[j + 1] = array[j];
j--;
}
array[j + 1] = key;
}
return array;
}
/**
* Sentinel sort is a function which on the first step finds the minimal element in the provided
* array and puts it to the zero position, such a trick gives us an ability to avoid redundant
* comparisons like `j > 0` and swaps (we can move elements on position right, until we find
* the right position for the chosen element) on further step.
*
* @param array The array to be sorted
* @param <T> The type of elements in the array, which must be comparable
* @return The sorted array
*/
public <T extends Comparable<T>> T[] sentinelSort(T[] array) {
if (array == null || array.length <= 1) {
return array;
}
final int minElemIndex = findMinIndex(array);
SortUtils.swap(array, 0, minElemIndex);
for (int i = 2; i < array.length; i++) {
final T currentValue = array[i];
int j = i;
while (j > 0 && SortUtils.less(currentValue, array[j - 1])) {
array[j] = array[j - 1];
j--;
}
array[j] = currentValue;
}
return array;
}
/**
* Finds the index of the minimum element in the array.
*
* @param array The array to be searched
* @param <T> The type of elements in the array, which must be comparable
* @return The index of the minimum element
*/
private <T extends Comparable<T>> int findMinIndex(final T[] array) {
int minIndex = 0;
for (int i = 1; i < array.length; i++) {
if (SortUtils.less(array[i], array[minIndex])) {
minIndex = i;
}
}
return minIndex;
}
}