算法-快速排序

快速排序是内部排序中交换排序的一种。

算法思想

1)选择一个基准元素,通常选择第一个元素或者最后一个元素,

2)通过一趟排序讲待排序的记录分割成独立的两部分,其中一部分记录的元素值均比基准元素值小。另一部分记录的 元素值比基准值大。

3)此时基准元素在其排好序后的正确位置

4)然后分别对这两部分记录用同样的方法继续进行排序,直到整个序列有序。

空间复杂度

O(1)

时间复杂度

最理想 O(nlogn) 最差时间O(n^2)

算法实现思想

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
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
class quick_sort {
/**
* 前后指针快排法
*/
public static void quickSortByTwoPointer(int[] a,int startIndex, int endIndex){
if (startIndex >= endIndex){
return;
}
int partitionIndex = getPartitionIndexByTwoPointer(a,startIndex,endIndex);
quickSortByTwoPointer(a, startIndex, partitionIndex-1);
quickSortByTwoPointer(a, partitionIndex + 1, endIndex);
}

private static int getPartitionIndexByTwoPointer(int[] a, int startIndex, int endIndex){
int left = startIndex;
int right = endIndex;
int pivot = a[startIndex];
while (left != right){
while (left < right && a[right] > pivot){
right --;
}
while (left < right && a[left] <= pivot){
left ++;
}
if (left < right){
a[left] = a[left] + a[right];
a[right] = a[left] - a[right];
a[left] = a[left] - a[right];
}
System.out.println("after replace "+Arrays.toString(a));
}
System.out.println("before change "+ Arrays.toString(a));
a[startIndex] = a[left];
a[left] = pivot;
System.out.println("after change "+Arrays.toString(a));
return left;
}

public static void quickSortByFillEmpty(int[] a, int startIndex, int endIndex){
if (startIndex > endIndex){
return;
}
int partitionIndex = getPartitionIndexByFillEmpty(a, startIndex,endIndex);
quickSortByFillEmpty(a, startIndex, partitionIndex-1);
quickSortByFillEmpty(a, partitionIndex +1, endIndex);
}

private static int getPartitionIndexByFillEmpty(int[] a, int startIndex, int endIndex){
int index = startIndex;
int left = startIndex;
int right = endIndex;
int pivot = a[startIndex];

while (left < right){
while (left < right){
if (a[right] < pivot){
a[index] = a[right];
index = right;
left ++;
break;
}
right --;
}
while (left < right){
if (a[left] > pivot){
a[index] = a[left];
index = left;
right --;
break;
}
left ++;
}
}
a[index] = pivot;
return index;
}

public static void main(String[] args) {
int[] a = new int[]{3,4,9,1,2,6,5,2,1};
System.out.println(Arrays.toString(a));
quickSortByTwoPointer(a,0, a.length-1);
System.out.println(Arrays.toString(a));
// int a = 1;
// int b = 2;
// a = a + b;
// b = a - b;
// a = a - b;
// System.out.println(a);
// System.out.println(b);
}
}

c实现

python实现