-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathHoarePartition.java
More file actions
67 lines (58 loc) · 1.76 KB
/
Copy pathHoarePartition.java
File metadata and controls
67 lines (58 loc) · 1.76 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
/**
* Partition using a variant of Hoare's partitioning method.
*/
public class HoarePartition implements PartitionAlgorithm {
// +-----------+---------------------------------------------------
// | Constants |
// +-----------+
/**
* It's a singleton class, right?
*/
public static final PartitionAlgorithm ALGORITHM = new HoarePartition();
// +---------+-----------------------------------------------------
// | Methods |
// +---------+
/**
* Get the name of the algorithm.
*/
public String name() {
return "Hoare";
} // name()
/**
* Partition the elements at positions [lb .. ub) of iarr.
*
* @param iarr the array to partition
* @param lb the lower bound of the subarray (inclusive)
* @param ub the upper bound of the subarray (exclusive)
* @return the index of the pivot
*/
public int partition(IntArray iarr, int lb, int ub) {
// Sanity check
if (lb >= ub) return lb;
// Pick a pivot and swap to the beginning.
int pivotLoc = lb + (int) Math.floor(Math.random() * (ub - lb));
iarr.swap(lb, pivotLoc);
int pivot = iarr.get(lb);
// Iterate through, moving things as appropriate
int small = lb+1;
int large = ub;
int left = 0;
int right = 0;
while (small < large) {
while ((small < large) && (left = iarr.get(small)) <= pivot) {
++small;
}
while ((small < large) && (right = iarr.get(large - 1)) > pivot) {
--large;
}
if (small < (large - 1)) {
iarr.set(small++, right);
iarr.set(--large, left);
}
} // while
// Swap the pivot back to the middle
iarr.swap(lb, small-1);
// And we're done.
return small-1;
} // partition
} // class HoarePartition