forked from dr-cs/intro-oop-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSort.java
More file actions
86 lines (73 loc) · 2.45 KB
/
Sort.java
File metadata and controls
86 lines (73 loc) · 2.45 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
import java.util.Arrays;
import java.util.Random;
public class Sort {
private static Random random;
public static <T extends Comparable<? super T>> void insertionSort(T[] a) {
for (int j = 1; j < a.length; ++j) {
assert isSorted(a, 0, j - 1);
T key = a[j];
int i = j - 1;
while(i >= 0 && (a[i].compareTo(key) > 0)) {
a[i + 1] = a[i];
i = i - 1;
}
a[i + 1] = key;
}
}
private static <T extends Comparable<? super T>>
boolean isSorted(T[] array, int start, int end) {
for (int i = start; i < end; ++i) {
if (!(array[i].compareTo(array[i + 1]) < 0))
return false;
}
return true;
}
public static <T extends Comparable<? super T>> void quickSort(T[] a) {
qs(a, 0, a.length - 1);
}
private static <T extends Comparable<? super T>>
void qs(T[] a, int begin, int end) {
if (begin >= end) { // Base case: nothing to sort
return;
}
int pivot = partition(a, begin, end);
qs(a, begin, pivot - 1);
qs(a, pivot + 1, end);
}
private static <T extends Comparable<? super T>>
int partition(T[] a, int begin, int end) {
T pivotValue = a[end];
int i = begin - 1;
for (int j = begin; j <= end - 1; j++) {
if (a[j].compareTo(pivotValue) <= 0) {
i++;
swap(a, i, j);
}
}
swap(a, i + 1, end);
return i + 1;
}
private static <T> void swap(T[] a, int i, int j) {
T tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
// Why isn't something like this in Arrays, like Collections.shuffle()?
public static <T> void shuffle(T[] array) {
if (random == null) { random = new Random(); }
int count = array.length;
for (int i = count; i > 1; i--) {
swap(array, i - 1, random.nextInt(i));
}
}
public static void main(String[] args) {
Integer[] a = {5, 2, 4, 6, 1, 3};
System.out.println("Unsorted aray: " + Arrays.toString(a));
insertionSort(a);
System.out.println("Insertion-sorted aray: " + Arrays.toString(a));
shuffle(a);
System.out.println("Shuffled aray: " + Arrays.toString(a));
quickSort(a);
System.out.println("Quicksorted aray: " + Arrays.toString(a));
}
}