快速排序简单实现

快速排序简单实现

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
public class QuickSort {

public static int partition(int[] arr, int low, int high){
if (arr == null || low >= arr.length || low < 0 || high >= arr.length || high < 0){
return -1;//错误入参
}
int pivotPos = low;
int pivot = arr[low];
while(low < high){
while (low < high && arr[high] >= pivot){
high--;
}
while (low < high && arr[low] <= pivot){
low++;
}
if (low < high) {
swap(arr, low, high);
}
}
swap(arr, pivotPos, low);
return low;
}


public static void swap(int arr[], int a, int b){
if (a >= arr.length || a < 0 || b >= arr.length || b < 0){
return;
}

int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}

public static void quickSort(int[] arr, int low, int high){
//递归实现
if (arr == null || low < 0 || high <= 0 || low>high)
return;
int k = partition(arr, low, high);
if (k < high){
quickSort(arr, k+1, high);
}

if (k > low){
quickSort(arr, low ,k-1);
}
}

public static void quickSortNonRecursion(int[] arr, int low, int high){
//非递归,使用stack保存partition返回值
if (arr == null || low < 0 || high <= 0 || low>high)
return;
Stack<Integer> temp = new Stack<>();
int i, j;
//(注意保存顺序)先将初始状态的左右指针压栈
temp.push(high);//先存右指针
temp.push(low);//再存左指针
while (!temp.empty()) {
i = temp.pop();//先弹出左指针
j = temp.pop();//再弹出右指针
if (i < j) {
int k = partition(arr, i, j);
if (k > i) {
temp.push(k - 1);//保存中间变量
temp.push(i); //保存中间变量
}
if (j > k) {
temp.push(j);
temp.push(k + 1);
}
}

}
}


public static void main(String[] args){
int[] arr = {8,4,5,1,3,66,6,6};
quickSort(arr, 0, arr.length-1);

for (int i : arr){
System.out.println(i);
}
}
}