forked from OneCodeMonkey/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionOptimized.java
More file actions
78 lines (68 loc) · 1.73 KB
/
InsertionOptimized.java
File metadata and controls
78 lines (68 loc) · 1.73 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
/**
* Sorts a sequence of strings from standard input using an optimized version of insertion
* sort that uses half exchanges instead of full exchanges to reduce data movement.
*
*/
/**
* The `InsertionOptimized` class provides static methods for sorting an
* array using an optimized version of insertion sort(with half exchanges and a
* sentinel)
*
*/
public class InsertionOptimized {
private InsertionOptimized() {}
// Rearranges the array in ascending order, using the natural order.
public static void sort(Comparable[] a) {
int n = a.length;
// put smallest element in position to serve as sentinel.
int exchanges = 0;
for(int i = n - 1; i > 0; i--) {
if(less(a[i], a[i - 1])) {
exchange(a, i, i - 1);
exchanges++;
}
}
if(exchanges == 0)
return;
// insertion sort with half exchanges.
for(int i = 2; i < n; i++) {
Comparable v = a[i];
int j = i;
while(less(v, a[j - 1])) {
a[j] = a[j - 1];
j--;
}
a[j] = v;
}
assert isSorted(a);
}
// Helper sorting functions
// is v < w ?
private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
// exchanges a[i] and a[j]
private static void exchange(Object[] a, int i, int j) {
Object swap = a[i];
a[i] = a[j];
a[j] = swap;
}
// Check if array is sorted (for debug)
private static boolean isSorted(Comparable[] a) {
for(int i = 1; i < a.length; i++)
if(less(a[i], a[i - 1]))
return false;
return true;
}
// print the array to standard output
private static void show(Comparable[] a) {
for(int i = 0; i < a.length; i++)
StdOut.println(a[i]);
}
// test
public static void main(String[] args) {
String[] a = StdIn.readAllStrings();
InsertionOptimized.sort(a);
show(a);
}
}