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

快速排序

时间:2015-09-26 23:50:22      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

#include<cstdio>

#include<ctime>

#include<cstdlib>

===================================================== 

void Swap(int& a,int& b){

    if(a!=b){

        a^=b;b^=a;a^=b;

    }

}

=====================================================

int  Partition(int *A,int p,int r)

{

 int x,i;

 x=A[r];

 i=p-1;

 for(int j=p;j<=r-1;++j)

 {

   if(A[j]<=x)    

        i++;//x为最后一个数,小于x, 不动(交换)本身(未有大于x的)

        Swap(A[i],A[j]);

 }

 Swap(A[++i],A[r]);

 return i;

}

 

  //已有大于x的时,再遇小于x:交换

    //i为最后一个小于等于x元素的下标。

 

 

=====================================================

void  QuickSort(int *A,int p,int r)

{

 if(p<r)

 {

  int q = Partition(A,p,r);

  QuickSort(A,p,q-1);

  QuickSort(A,q+1,r);

 }

}

 

 

 

#include<cstdio>  

#include<ctime>  

#include<cstdlib>  

  

inline void Swap(int &a, int &b)  

{  

    if(a!=b)  

    {  

        a^=b;  

        b^=a;  

        a^=b;  

    }  

}  

  

int Partition(int *A,int front,int end)  

{  

    int key = A[end];  

    int i = front - 1;  

  

    for(int current = front;current < end;++current)  

    {  

        if(A[current]<=key)  

            Swap(A[++i],A[current]);  

    }  

    Swap(A[++i],A[end]);  

    return i;  

}  

  

void QuickSort (int *A,int front,int end)  

{  

    if(front < end)  

    {  

        int midPosition = Partition(A,front,end);  

        QuickSort(A,front,midPosition-1);  

        QuickSort(A,midPosition+1,end);  

    }  

}

 

快速排序

标签:

原文地址:http://www.cnblogs.com/lsx1993/p/4841481.html

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