zoukankan      html  css  js  c++  java
  • 快速排序的C语言实现及其时间复杂度

    快速排序:

    其思想为:在一个序列中,我们指定一个数(比如a[0]),然后查看整个数列,让比a[0]小的数都放到a[0]之前,比a[0]大的数都放到a[0]之后,那么a[0]所在的位置就是排好序后它应该待的位置。然后我们再对这个处理过的数列的前半部分用快速排序的方法排序,对后半部分用快速排序的算法进行排序,这样整个数列就排好序了。

    Base Case:如果被a[0]分成的两部分只有一个元素或者没有元素,那么说明这个序列就已经排好序了。

    代码:

    /*Quick sort
    *Author: Eric
    *Time: 2011.01.10
    */

    #include <stdio.h>

    /*Partion the position of the a[0], start and end is the true subscripes*/
    int partition(int *a, int start, int end)
    {
    int i = start + 1,
    j = end;
    int temp = 0;
    while(i < j)
    {
    while(a[i] <= a[start]) //Find the first element bigger than a[start]
    i++;
    while(a[j] > a[start]) //Find the first element smaller or equal to a[start]
    j--;
    if(i <= j-1)
    {
    temp = a[i];
    a[i] = a[j];
    a[j] = temp;
    }

    if(i == j-1)
    break;
    else if(i > j-1)
    {
    i = j;
    break;
    }
    }
    if(a[i] <= a[start])
    {
    temp = a[start];
    a[start] = a[i];
    a[i] = temp;
    }

    return i;
    }

    void quick_sort(int *a, int start, int end)
    {
    int mid = 0;
    if(end > start)
    {
    mid = partition(a, start, end);
    quick_sort(a, start, mid-1);
    quick_sort(a, mid+1, end);
    }
    }

    int main()
    {
    int a[100] = {5, 2, 4, 3, 1, 7, 2, 6, 18, 14,
    5, 2, 4, 3, 1, 7, 2, 6, 18, 14,5, 2, 4, 3, 1, 7, 2, 6, 18, 14,5, 2, 4, 3, 1, 7, 2, 6, 18, 14,
    5, 2, 4, 3, 1, 7, 2, 6, 18, 14,5, 2, 4, 3, 1, 7, 2, 6, 18, 14,5, 2, 4, 3, 1, 7, 2, 6, 18, 14,
    5, 2, 4, 3, 1, 7, 2, 6, 18, 14,5, 2, 4, 3, 1, 7, 2, 6, 18, 14,5, 2, 4, 3, 1, 7, 2, 6, 18, 14};
    quick_sort(a, 0, 99);
    printf("The a[100] is:");
    int i = 0;
    for(i = 0; i < 100; i++)
    printf(" %d", a[i]);
    printf("\n");

    return 0;
    }
     

    时间复杂度为Θ(nlgn)

  • 相关阅读:
    HDU5320 : Fan Li
    BZOJ3069 : [Pa2011]Hard Choice 艰难的选择
    BZOJ4227 : 城市
    BZOJ4216 : Pig
    BZOJ1171 : 大sz的游戏
    BZOJ4182 : Shopping
    BZOJ3482 : [COCI2013]hiperprostor
    BZOJ3919 : [Baltic2014]portals
    BZOJ3711 : [PA2014]Druzyny
    BZOJ1580 : [Usaco2009 Hol]Cattle Bruisers 杀手游戏
  • 原文地址:https://www.cnblogs.com/wangshuo/p/1931990.html
Copyright © 2011-2022 走看看