-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
138 lines (117 loc) · 3.33 KB
/
QuickSort.java
File metadata and controls
138 lines (117 loc) · 3.33 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package class01;
/**
* @author pacai
* @version 1.0
*/
public class QuickSort {
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void quickSort1(int[] arr) {
if (arr == null || arr.length < 2) {
return;
}
process1(arr, 0, arr.length - 1);
}
public static void process1(int[] arr, int L, int R) {
if (L > R) {
return;
}
int mid = partition(arr, L, R);
process1(arr, L, mid - 1);
process1(arr, mid + 1, R);
}
public static void quickSort2(int[] arr) {
if (arr == null || arr.length < 2) {
return;
}
}
public static void process2(int[] arr, int L, int R) {
if (L > R) {
return;
}
int[] midArr = netherlandsFlag1(arr, 0, R);
process2(arr, L, midArr[0] - 1);
process2(arr, midArr[1] + 1, R);
}
public static void quickSort3(int[] arr) {
if(arr == null || arr.length < 2) {
return;
}
process3(arr, 0, arr.length - 1);
}
public static void process3(int[] arr, int L, int R){
if(L >= R){
return;
}
swap(arr, (int)(Math.random() * (R - L + 1)), R); //随机选出一个数来作为准则
int[] midArr = netherlandsFlag1(arr, 0, R);
process3(arr, L, midArr[0] - 1);
process3(arr, midArr[1] + 1, R);
}
public static int partition(int[] arr, int L, int R) {
if (L > R) {
return -1;
}
if (L == R) {
return L;
}
int lessEqual = L - 1;
int index = L;
while (index < R) {
if (arr[index] <= arr[R]) {
swap(arr, index, ++lessEqual);
}
index++;
}
swap(arr, ++lessEqual, R);
return lessEqual;
}
@SuppressWarnings("all")
public static int[] netherlandsFlag1(int[] arr, int L, int R) {
if (L > R) {
return new int[]{-1, -1};
}
if (L == R) {
return new int[]{L, R};
}
int less = L - 1;
int index = L;
int more = R;
while (index < more) { //撞上右边界结束
if (arr[index] == arr[R]) {
index++;
} else if (arr[index] > arr[R]) {
swap(arr, index, --more);
} else {
swap(arr, index++, ++less);
}
}
swap(arr, R, more);
return new int[]{less + 1, more};
}
public static int[] netherlandsFlag2(int[] arr, int L, int R) {
if (L > R) {
return new int[]{-1, -1};
}
if (L == R) {
return new int[]{L, R};
}
int less = L - 1;
int index = L;
int more = R + 1;
int val = arr[R];
while (index < more) {
if (arr[index] == val) {
index++;
} else if (arr[index] > val) {
swap(arr, index, --more);
} else {
swap(arr, index++, ++less);
}
}
return new int[]{less + 1, more};
}
}