-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
76 lines (68 loc) · 1.36 KB
/
Copy pathQuickSort.java
File metadata and controls
76 lines (68 loc) · 1.36 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
import java.util.Random;
/**
*
* @author KAKANAKOU MIGUEL
*
*/
public final class QuickSort {
/**
* Use the Quicksort method to sort the given array A
*
* @param A Array of Comparable that contains the object to sort
*/
public static void sort(Comparable[] A) {
if (A == null)
return;
shuffle(A);
sort(A, 0, A.length - 1);
}
private static void sort(Comparable[] A, int lo, int hi) {
if (lo >= hi)
return;
int k = partition(A, lo, hi);
sort(A, lo, k - 1);
sort(A, k + 1, hi);
}
private static int partition(Comparable[] A, int lo, int hi) {
int i = lo + 1;
int j = hi;
while (true) {
while ((i < j) && !less(A[lo], A[i]))
i++;
while (less(A[lo], A[j]))
j--;
if (i >= j)
break;
swap(A, i, j);
i++;
j--;
}
swap(A, lo, j);
return j;
}
private static void shuffle(Comparable[] A) {
Random rdm = new Random();
int r = 0;
for (int i = 0; i < A.length; i++) {
r = rdm.nextInt(i + 1);
swap(A, i, r);
}
}
private static void swap(Comparable[] A, int i, int j) {
Comparable k = A[i];
A[i] = A[j];
A[j] = k;
}
private static boolean less(Comparable a, Comparable b) {
int cmp = a.compareTo(b);
if (cmp < 0)
return true;
return false;
}
private static boolean equals(Comparable a, Comparable b) {
int cmp = a.compareTo(b);
if (cmp == 0)
return true;
return false;
}
}