码迷,mamicode.com
首页 > 其他好文 > 详细

快速排序

时间:2014-10-07 00:58:03      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   ar   for   strong   sp   art   c   

主要是是一个分治算法。

形象地看就是 挖坑+递归


1. A[p,r]分为A[p,q-1]和A[q+1,r]两部分,要求A[p,r]<q<A[q+1,r].
2. 对A[p,r]和A[q+1,r]进行快速排序


#include<stdio.h>

int partition(int a[],int left,int right)
{
    int i=left;
    int j=right;
    int temp=a[i];
    while(i<j)
    {
        while(i<j && a[j]>=temp)
            j--;
            if(i<j)
                a[i]=a[j];
        while(i<j && a[i]<=temp)
            i++;
            if(i<j)
                a[j]=a[i];
    }
    a[i]=temp;
    return i;
}
void quickSort(int a[],int left,int right)
{
    int dp;
    if(left<right)
    {
        dp=partition(a,left,right);
        quickSort(a,left,dp-1);
        quickSort(a,dp+1,right);
    }
}

int main()
{
    int a[9]={5,4,9,1,7,6,2,3,8};
    quickSort(a,0,8);
    for(int i=0;i<9;i++)
    {
        printf("%d ",a[i]);
    }
    return 0;
}


Reference

[1].http://blog.csdn.net/v_july_v/article/details/6116297

[2].http://blog.csdn.net/morewindows/article/details/6684558

[3].http://www.cnblogs.com/foreverking/articles/2234225.html

[4].算法导论. Page96~106

快速排序

标签:blog   http   io   ar   for   strong   sp   art   c   

原文地址:http://my.oschina.net/lvyi/blog/324551

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