-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathquick.java
55 lines (48 loc) · 1.09 KB
/
quick.java
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
package sortingAlgorithm;
public class quick {
public static void main(String[] args) {
int[] a = {4, 2, 1, 6, 3, 0, -5, -2};
System.out.println("排序前的数组为:");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
System.out.println();
quickSort(a, 0, a.length-1);
System.out.println("排序后的数组为:");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
System.out.println();
}
static void quickSort(int[] a, int left, int right){ // 快速排序算法
int mid,t;
int ltemp,rtemp;
ltemp = left;
rtemp = right;
mid = a[(left+right)/2]; // 分界值
while(ltemp<rtemp){
while(a[ltemp]<mid){
ltemp++;
}
while(a[rtemp]>mid){
rtemp--;
}
if(ltemp<=rtemp){
t=a[ltemp];
a[ltemp]=a[rtemp];
a[rtemp]=t;
ltemp++;
rtemp--;
}
}
if(ltemp==rtemp){
ltemp++;
}
if(left<rtemp){
quickSort(a, left, ltemp-1); // 递归调用
}
if(ltemp<right){
quickSort(a, rtemp+1, right); // 递归调用
}
}
}