[快速排序] 经典排序算法

#include<stdio.h>
#include<stdlib.h>


int num;//数组元素总数


/**=======================
*display函数
*参数:数组首地址(*a)
*返回值:无
*作用:输出数组
*=========================
*/
void display(int *a){
for(int i=0;i<num;i++){
    printf("%d  ",a[i]);
}
}


/**=======================
*qSort函数
*参数:起始值(st),终值(en),数组首地址(*a)
*返回值:无
*作用:快速排序核心算法
*=========================
*/
void qSort(int st,int en,int *a){
    int mid,i=st,j=en,temp;
    if(st<en){
        mid=(st+en)>>1;//求出中值


        while((i)<(j)){//这个循环用于交换中值两边的数据,大者在右
            if(a[i]>a[j]){
                temp=a[i];a[i]=a[j];a[j]=temp;//交换
            }
            i++;j--;//向中间靠近
        }


        qSort(st,mid,a);//递归左边
        qSort(mid+1,en,a);//递归右边,mid必须加1,否则无法退出递归
    }
}


int main(){
int *a;


printf("please input the amount of the array: ");//为数组动态分配空间
scanf("%d",&num);
a=(int*)malloc(sizeof(int)*num);


for(int i=0;i<num;i++){//为数组赋值
    scanf("%d",&a[i]);
}


qSort(0,num-1,a);//进行排序


display(a);//输出排序结果


return 0;
}

猜你喜欢

转载自blog.csdn.net/the_first_snow/article/details/78801477