-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOptimizedQuick.java
More file actions
59 lines (53 loc) · 1.91 KB
/
OptimizedQuick.java
File metadata and controls
59 lines (53 loc) · 1.91 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
package T1;
public class OptimizedQuick extends SortAlgorithm{
public void sort(Comparable[] objs){
qsort(objs,0,objs.length-1);
}
Insertion alg = new Insertion();
public void qsort(Comparable[] objs,int i,int j){
while(true) {
int k = partition(objs, i, j - 1, movePivot(objs, i, j));//移动轴值
exchange(objs, k, j);
if ((k - i) <40){
alg.sort(objs,i,k+1);
}
else{
qsort(objs,i,k-1);
}
if ((j - k) > 1) {
i = k+1;
continue;
}
return;
}
}
public Comparable movePivot(Comparable[] objs,int left,int right) { //查询轴值
int mid = left + (right - left) / 2;
if(less(objs[right],objs[mid])){
exchange(objs,right,mid); //把right和mid的key值小者放到mid处
}
if(less(objs[mid],objs[left])){
exchange(objs,left,mid);
}
if(less(objs[right],objs[mid])){
exchange(objs,mid,right);
}
return objs[right]; //返还轴值
}
public int partition(Comparable[] objs, int left, int right, Comparable pivot) { //使用双指针分治
while (left <= right) { //让双指针相遇
while (less(objs[left], pivot)) {
left++;
}
while (right >-1 && (less(pivot, objs[right]) || objs[right].equals(pivot))) {
right--;
}
if(right<0){
return left; // 如果right<0,说明left未移动,数据交界点就是left
}
exchange(objs, left, right);
}
exchange(objs, left, right);
return left; // 返还交界点的记录
}
}