码迷,mamicode.com
首页 > 编程语言 > 详细

快速排序

时间:2019-09-20 00:04:02      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:col   printf   eve   最坏情况   oid   onclick   display   顺序   nbsp   

技术图片
/******************************************************
快速排序:稳定排序
最好情况:T=O(n*logn)//待排序序列越无序,算法效率越高
最坏情况:T=O(n*n) //待排序列越有序,算法效率越低
*******************************************************/
#include <stdio.h>
#include <stdbool.h>

int main()
{
    int a[5],i;
    printf("请输入5个数据:\n");
    for(i=0;i<5;i++)
    {
        scanf("%d",&a[i]);
    }
    Partition(a,0,4); //划分操作
    QuickSort(a,0,4); //排序操作
    printf("快排后顺序为:\n");
    for(i=0;i<5;i++)
        printf("%d ",a[i]);
    return 0;
}
int Partition(int A[],int low, int high) //low当前待排元素序列的起始下标,high是末尾下标
{
    int pivot = A[low]; //第一个元素作为枢轴
    while(low<high)
    {
        while(low<high&&A[high]>pivot)  --high; //此处的low<high是防止完全顺序的序列出现数组下溢,先从末尾往前找到第一个比枢轴小的元素
        A[low] = A[high];//用high 的元素替换low的元素
        while(low<high&&A[low]<pivot)   ++low; //再从开头往后找到第一个比枢轴大的元素
        A[high] = A[low];  //用low的元素替换high的元素
    }
   A[low] = pivot; //枢轴元素放在最终的位置上
   return low; //返回存放枢轴的最终位置
}
void QuickSort (int A[],int low,int high)
{
    if(low<high) //low和high值要合法
    {
        int pivotpos = Partition(A,low,high);
        QuickSort(A,low,pivotpos-1); //分治递归左半部分
        QuickSort(A,pivotpos+1,high);
    }
}
View Code

 

快速排序

标签:col   printf   eve   最坏情况   oid   onclick   display   顺序   nbsp   

原文地址:https://www.cnblogs.com/spore/p/11553245.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!