c++版:
#include <iostream>
//快速排序
void quick_sort(int s[], int l, int r)
{
if (l < r)
{
std::swap(s[l], s[(l + r) / 2]); //将中间的这个数和第一个数交换 参见注1
int i = l, j = r, x = s[l];
while (i < j)
{
while(i < j && s[j] >= x) // 从右向左找第一个小于x的数
j--;
if(i < j)
s[i++] = s[j];
while(i < j && s[i] < x) // 从左向右找第一个大于等于x的数
i++;
if(i < j)
s[j--] = s[i];
}
s[i] = x;
quick_sort(s, l, i - 1); // 递归调用
quick_sort(s, i + 1, r);
}
}
int main(){
int A[5] ={2, 4, 1, 3, 5};
quick_sort(A, 0, 4);
for (int i = 0; i<5; ++i) {
if(i) printf(" ");
printf("%d", A[i]);
}
return 0;
}
c++精简版:
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include <cmath>
using namespace std;
int Partition(int A[], int left, int right){
int p = round(1.0*rand()/RAND_MAX*(right - left) + left);
swap(A[p], A[left]);
int temp = A[left];
while(left < right> temp) right--;
A[left] = A[right];
while(left<right && A[left] <= temp) left++;
A[right] = A[left];
}
A[left] = temp;
return left;
}
void quickSort(int A[], int left , int right){
if (left<right){
int pos = Partition(A, left, right);
quickSort(A, left, pos -1);
quickSort(A, pos + 1, right);
}
}
int main(){
int A[5] ={2, 4, 1, 3, 5};
quickSort(A, 0, 4);
for (int i = 0; i < 5; ++i) {
if(i) printf(" ");
printf("%d", A[i]);
}
return 0;
}
python 版:
def quick_sort(li):
# 被分解的Nums小于1则解决了
if len(li) <= 1:
return li
# 分解
temp = li[0]
left = [i for i in li[1:] if i < temp xss=removed>= temp]
# 递归求解即分治
left = quick_sort(left)
right = quick_sort(right)
# 合并
return left + [temp] + right
quick_sort(nums2)
转载自:https://blog.csdn.net/morewindows/article/details/6684558
https://www.runoob.com/w3cnote/quick-sort.html