首页 > 代码库 > 快速排序

快速排序

快排用到了分治思想和递归思想。效率不稳定,平均复杂度在维持在O(n*logn),可见,在n较大时应用较好。

 

#include <iostream>using namespace std;int a[200] = {564,321,1,2,3,654,21};void quick_sort(int left,int right){    if(left>right)        return;        int temp = a[left];    int i= left;    int j = right;        while(i!=j)    {        while(a[j]>=temp&&i<j)        {            j--;        }                while(a[i]<=temp&&i<j)        {            i++;        }                if(i<j)        {            a[i] = a[i] + a[j];            a[j] = a[i] - a[j];            a[i] = a[i] - a[j];        }    }        a[left] = a[i];    a[i] = temp;        quick_sort(left,i-1);    quick_sort(i+1,right);}int main(){    quick_sort(0,6);        for(int i=0;i<7;i++)    {    cout<<a[i]<<" ";    }        return 0;}

 

快速排序