快速排序

快速排序运用的思想是分治,把一组大规模的待排序的数分解成两个组小规模的数;另外当待排序的数比较少时快速排序并不高效,因此在序列长度小于5的时候使用插入排序。

#include<iostream>
#include<stdlib.h>
using namespace std;
int list[] = {6,8,7,9,5,2,1,3,4,0};
void sort(int* list,int m, int n){
    int tag = 1;
    int i,j;
    int temp;
    for(i = tag;i<=n;i++){
        temp = list[i];
        for(j = i ;j>m;j--){
            if(list[j-1]>temp){
                list[j] = list[j-1];
            }
            else{
                break;
            }
        }
        list[j] = temp;
    }
    return;
} 
void quickSort(int *list,int m ,int n){
    if(n-m<5){
        cout<<"
sort("<<"m,n:"<<m<<","<<n<<")";
        sort(list,m,n);
        return;
    }
    int t,i,j;
    i = m+1;
    j = n;
    while(i<j){
        for(i = m+1;i<=n;i++){
            if(list[i]>list[m])
                break;
        }
        for(j = n;j>m;j--){
            if(list[j]<list[m])
                break;
        }
        if(i<j){
            t = list[i];
            list[i] = list[j];
            list[j] = t;            
        }
    cout<<"
";
    for(int k = 0;k<10;k++){
        cout<<list[k]<<" ";
    }
    }
    t = list[m];
    list[m] = list[j];
    list[j] = t;
    cout<<"
"<<"quickSort("<<m<<","<<j-1<<")";
    quickSort(list,m,j-1);
    cout<<"
"<<"quickSort("<<j+1<<","<<n<<")";
    quickSort(list,j+1,n);
}
int main(){
    int i;
    for(i = 0;i<10;i++){
        cout<<list[i]<<" ";
    }
    //sort(list,0,9);
    quickSort(list,0,9);
    cout<<"
";
    for(i = 0;i<10;i++){
        cout<<list[i]<<" ";
    }
    getchar();
    return 0;
}
View Code

原文地址:https://www.cnblogs.com/yuanzhenliu/p/5316110.html