-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
90 lines (79 loc) · 2.39 KB
/
QuickSort.java
File metadata and controls
90 lines (79 loc) · 2.39 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
package sorting_searching;
import java.util.Comparator;
public class QuickSort {
public static void main(String[] args) {
// Example:
int[] array = {91, 34, 86, 39, 27, 87, 70, 48, 100, 95};
quickSort(array);
System.out.println(java.util.Arrays.toString(array)); // [27, 34, 39, 48, 70, 86, 87, 91, 95, 100]
}
public static void quickSort(int[] a) {
quickSort(a, 0, a.length - 1);
}
private static void quickSort(int[] a, int left, int right) {
if (left >= right) {
return;
}
int k = partition(a, left, right);
quickSort(a, left, k - 1);
quickSort(a, k + 1, right);
}
public static <T extends Comparable<? super T>> void quickSort(T[] a) {
quickSort(a, Comparator.naturalOrder(), 0, a.length - 1);
}
public static <T> void quickSort(T[] a, Comparator<T> comp) {
quickSort(a, comp, 0, a.length - 1);
}
private static <T> void quickSort(T[] a, Comparator<T> comp, int left, int right) {
if (left >= right) {
return;
}
int k = partition(a, comp, left, right);
quickSort(a, comp, left, k - 1);
quickSort(a, comp, k + 1, right);
}
private static int partition(int[] a, int left, int right) {
int i = left;
int j = right - 1;
int pivot = a[right];
do {
while (i < right && a[i] < pivot) {
++i;
}
while (j > left && a[j] > pivot) {
--j;
}
if (i < j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
} while (i < j);
int temp = a[i];
a[i] = a[right];
a[right] = temp;
return i;
}
private static <T> int partition(T[] a, Comparator<T> comp, int left, int right) {
int i = left;
int j = right - 1;
T pivot = a[right];
do {
while (i < right && comp.compare(a[i], pivot) < 0) {
++i;
}
while (j > left && comp.compare(a[j], pivot) > 0) {
--j;
}
if (i < j) {
T temp = a[i];
a[i] = a[j];
a[j] = temp;
}
} while (i < j);
T temp = a[i];
a[i] = a[right];
a[right] = temp;
return i;
}
}