快速排序

快速排序思想:以一维数组为例,选择最左边的元素为基准点,先从右往左找小于基准点的数,再从左往右找大于基准点的数,然后交换他们。再继续……直到两个索引相等的时候相遇了,交换相遇这个点和基准点的值,再以此为中点分成两个部分(二分法),对这两部分再次重复上述操作……直到不能再分。

#include <stdio.h>

int array[100],num;
void quicksort(int left,int right)
{
    int base,i,j,temp;
    if(left > right)
        return;
    i = left;
    j = right;
    base = array[left];//最左边作为基准点并保存基准点的值

    while(i != j) //当两个索引没有相遇时,一直检索
    {
        while(array[j] >= base && i < j)//先从右往左
            j--;
        while(array[i] <= base && i < j)//再从左往右
            i++;
        if(i < j)//两个循环都跳出了,并且索引没有相遇,交换两个值
        {
            temp = array[j];
            array[j] = array[i];
            array[i] = temp;
        }       
    }//跳出了循环说明两个索引的值相遇了
    array[left] = array[i];//交换两遍索引相遇的点和原来基准点的值
    array[i] = base;
    //检索一趟相遇后就二分再检索
    quicksort(left,i-1);//二分法,把数组分成两个部分,每部分继续
    quicksort(i+1,right);
    return;
}

int main()
{
    int i;
    printf("Please input numbers of elements in the array:\n");
    scanf("%d",&num);
    for(i=0;i<num;i++)
    {
        printf("Please input %d element in the array:\n",i);
        scanf("%d",&array[i]);
    }
    quicksort(0,num-1);
    for(i=0;i<num;i++)
    {
        printf("%d ",array[i]);
    }
    return 0;   
}

输入以及运行结果:

Please input numbers of elements in the array:
8
Please input 0 element in the array:
96
Please input 1 element in the array:
69
Please input 2 element in the array:
36
Please input 3 element in the array:
56
Please input 4 element in the array:
24
Please input 5 element in the array:
85
Please input 6 element in the array:
35
Please input 7 element in the array:
75
24 35 36 56 69 75 85 96 Press any key to continue

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值