quick sort

explanation

time complexity: O(nlogn)
每层 partition O(n), log 表示每次partition分的很平均, 有logn层
worst cast: O(n^2), 每次都选到最小值/最大值
space complexity:O(1)

code

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


import java.io.*;
import java.util.*;
class {
public static void main (String[] args) {
System.out.println("Hello Java");
int[] a= {3, 2,1};
int[] b = quickSort(a);
System.out.println(Arrays.toString(b));

}

public static int[] quickSort(int[] arr) {
if (arr == null || arr.length <= 1) {
return arr;
}
sort(arr, 0, arr.length - 1);

return arr;
}

private static void sort(int[] arr, int left, int right) {
if (left >= right) {
return;
}

int pivot = partition(arr, left, right);

sort(arr, left, pivot - 1);
sort(arr, pivot + 1, right);
}

private static int partition(int[] arr, int left, int right) {
int pivotIndex = findPivot(left, right);
int pivot = arr[pivotIndex];
// swap the pivot to the rightmost position
swap(pivotIndex, right, arr);

int leftBound = left, rightBound = right - 1;
while (leftBound <= rightBound) {
if (arr[leftBound] < pivot) {
leftBound++;

} else if (arr[rightBound] >= pivot) {
rightBound--;

} else {
swap(leftBound, rightBound, arr);
leftBound++;
rightBound--;

}
}
swap(right, leftBound, arr);
return leftBound;

}

private static void swap(int i, int j, int[] arr) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

private static int findPivot(int left, int right) {
Random rand = new Random();
return left + rand.nextInt(right - left + 1); // 0 inclusive, right - left + 1 exclusive

}
}