# 面试官，您要的快排

pezy

## 简式快排

``````void quicksort(int arr[], int l, int r) {
if (l < r) {
int pivot = partition(arr, l, r);
quicksort(arr, l, pivot-1);
quicksort(arr, pivot+1, r);
}
}``````

``````int partition(int arr[], int l, int r) {
int k = l, pivot = arr[r];
for (int i = l; i < r; ++i)
if (arr[i] <= pivot) std::swap(arr[i], arr[k++]);
std::swap(arr[k], arr[r]);
return k;
}``````

``````
3,7,8,5,2,1,9,5,4
``````

``````3,2,1,4,7,8,9,5,5
^^^^^ | ^^^^^^^^^
``````

## 来份三明治

``````5 7 4 3 1 2 6 5 5
``````

``````4 3 1 2 5 5 5 7 6
^^^^^^^ |   | ^^^
``````

``````// 3-way partition
std::pair<int, int> partition(int arr[], int l, int r) {
int k = l, p = r;
for (int i = l; i < p; )
if (arr[i] < arr[r]) std::swap(arr[i++], arr[k++]);
else if (arr[i] == arr[r]) std::swap(arr[i], arr[--p]);
else ++i;
// move pivots to centre
int m = std::min(p-k, r-p+1);
for (int i = 0; i < m; ++i)
std::swap(arr[k+i], arr[r-i]);
return std::make_pair(k, r-p+k);
}``````

`quicksort` 也需要稍稍改变一点：

``````void quicksort(int arr[], int l, int r) {
if (l < r) {
auto pivot = partition(arr, l, r);
quicksort(arr, l, pivot.first-1);
quicksort(arr, pivot.second+1, r);
}
}``````

3.1k 声望
330 粉丝
0 条评论