快速排序

来源:互联网 发布:c语言关键字scanf 编辑:程序博客网 时间:2024/05/02 00:06
    我们都知道冒泡排序是排序里面最简单的排序,很容易理解的一个排序算法。但它的时间复杂度为O(n^2)的,快速排序是对冒泡排序的一种改进,基本思想是,通过一轮排序将待排记录分割为独立的两部分,其中一部分的记录的关键字都比另一部分的关键字小,然后再分别对者两部分记录继续排序,最终完成排序工作。
假如待排序的数组为
49 38 65 97 76 13 27 49.经过一轮快速排序后变成
27 38 13 49 76 97 65 49,即49前面的都比49小,后边的都比49大。再分别对这两个部分快速排序,又可以将前后部分再次分割,直到有序为止。也就是通过递归来实现的。

         从上面可以看出每次的调整及中枢的位置是关键,具体做法是附加两个指针low和high,它们的初值是low和high,设中枢记录的关键字为pivotkey,则首先从high所指位置起向前搜索找到第一个关键字小于pivotkey的记录和中枢记录互相交换(就是将小的放到前边去,因为要把数组升序的)。然后从low所指位置向后搜索,找到第一个关键字大于pivotkey的记录和中枢记录相互交换,重复这两步,直到low=high。

代码如下

    //    //               快速排序    //    //          Created by GPH on 13-6-9.    //  Copyright (c) 2013年 GPH. All rights reserved.    //        #include <stdio.h>    //执行完后low之前的比a[low]小,之后的比a[low]大    int Partition(int a[],int low,int high)    {        int pivotkey = a[low];        int tmp = a[low];        while (low < high)        {            while (low < high && a[high] >= pivotkey )            {                high--;            }            a[low] = a[high];                        while (low < high && a[low] <= pivotkey )            {                low++;            }            a[high] = a[low];        }                a[low] = tmp;        return low;    }    //快速排序    void QSort(int a[],int low,int high)    {        if (low < high)        {            int pivotloc = Partition(a, low, high);            QSort(a, low, pivotloc-1);            QSort(a, pivotloc+1, high);        }    }        int main()    {        int a[8] = {49,38,65,97,76,13,27,49};        QSort(a, 0, 7);                for (int i = 0; i < 8; i++)        {           printf("%d ",a[i]);        }                printf("\n");        return 0;    }


0 0