快速排序partation的实现

来源:互联网 发布:云计算及大数据 教材 编辑:程序博客网 时间:2024/06/08 05:55

将数组视为三部分,一部分为<=key,边界为i,另一部分>=key,剩下的为要处理的元素,下标为j。如果a[j]<=x,将i++,同时a[j]和a[i]交换。


#include<stdlib.h>#include<stdio.h>void exch(int &a,int &b){//exchange elem     int tmp;    tmp = a;    a= b;    b = tmp;}int partation(int a[],int p,int q){    int j;    int i = p;    int x = a[p];//set a[p] as key elem    for(j= p+1;j<=q;j++){//traverse the elem to be deal with        if(a[j]<=x){           i++;           if(i != j)             exch(a[j],a[i]);        }    }    exch(a[p],a[i]);// at last swap key and the boundry elem of the part which less than the key    return i;}void q_sort(int a[],int p,int q){    if(p<q){    int m = partation(a,p,q);    q_sort(a,p,m-1);    q_sort(a,m+1,q);    }}int main(){   int array[] = {4,7,4,2,19,8,7,64,3,2,1,0,9,6,4,7,4,2,1,6,8};   int array_size = sizeof(array)/sizeof(int);   q_sort(array,0,array_size-1);   for(int i =0 ;i<array_size;i++)        printf("%d ",array[i]);  return 1;}



原创粉丝点击