forked from joyang1/JavaInterview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort1.java
More file actions
57 lines (41 loc) · 1.12 KB
/
Copy pathQuickSort1.java
File metadata and controls
57 lines (41 loc) · 1.12 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
package sort;
import java.util.Arrays;
/**
* @author TommyYang on 2019-04-12
*/
public class QuickSort1 implements IArraySort {
public void quickSort(int[] arr, int left, int right) {
if(left >= right){
return;
}
int partition = partition(arr, left, right);
quickSort(arr, left, partition - 1);
quickSort(arr, partition + 1, right);
}
public int partition(int[] arr, int i, int j) {
int pivot = arr[i];
while (i < j) {
while (i < j && arr[j] > pivot)
j--;
if (i < j) {
arr[i] = arr[j];
i++;
}
while (i < j && arr[i] < pivot)
i++;
if (i < j) {
arr[j] = arr[i];
j--;
}
}
arr[i] = pivot;
return i;
}
@Override
public int[] sort(int[] sourArr) throws Exception {
// 对 arr 进行拷贝,不改变参数内容
int[] arr = Arrays.copyOf(sourArr, sourArr.length);
quickSort(arr, 0, arr.length - 1);
return arr;
}
}