3

我使用荷兰国旗分区技术实现快速排序。 http://ideone.com/WgAiGG

对于普通的快速排序。
http://ideone.com/GOE5Jl

使用荷兰国旗分区技术的快速排序代码

#include<iostream>
#include<time.h>
using namespace std;

void partition (int *a, int s, int e, int &start, int &end)
{
     start=s-1; 
     int mid=s;
     end=e;

     int pivot=a[e],temp,i;

     while (mid < end)
     {
           if  (a[mid] < pivot)
           {
               temp = a[start+1];
               a[start+1] = a[mid];
               a[mid] = temp;
               start++;
               mid++;     
           }
           else if (a[mid] == pivot)
           {
                mid++;
           }
           else
           {
               temp = a[end-1];
               a[end-1] = a[mid];
               a[mid] = temp;
               end--;
           }
     }
     temp = a[mid];
     a[mid] = a[e];
     a[e] = temp;
     cout<<start<<" "<<end<<"\n";
}

void Qsort(int *a, int s, int e)
{
     if (s>=e)
        return;
     int start,end;
     partition(a,s,e,start,end);
     Qsort(a,s,start);
     Qsort(a,end+1,e);
}

int main()
{
    int a[100];
    int i,j;
    int n = sizeof(a)/sizeof(a[0]);
    srand(time(NULL));
    for (j=0;j<n;j++)
    {
        a[j] = rand()%40;
        cout<<a[j]<<" ";
    }
    clock_t start = clock();
    Qsort(a,0,n-1);

    for (i=0;i<n;i++)
    {
        cout<<a[i]<<"  ";
    }
    cout<<"\nTime elapsed: "<<((double)clock() - start) / CLOCKS_PER_SEC<<endl;

}

普通快速排序的代码

#include<iostream>

#include<time.h>
using namespace std;

int partition (int *a, int s, int e)
{
    int i=s;
    int j=e-1;
    int pivot = a[e],temp;
    while (i<=j)
    {
          if  (a[i] < pivot)
          {
              i++;
              continue;
          }
          if  (a[j] > pivot)
          {
              j--;
              continue;
          }

          temp = a[i];
          a[i] = a[j];
          a[j] = temp;
          i++;
          j--;
    }

    temp = a[i];
    a[i] = a[e];
    a[e] = temp;
    return i;
}


void qsort (int *a, int s, int e)
{
     if  (s>=e)
     {
         return;
     }
     int i = partition (a,s,e);
     qsort(a,s,i-1);
     qsort(a,i,e);
}


int main()
{
    int a[100];
    int i,j;
    int n = sizeof(a)/sizeof(a[0]);
    srand(time(NULL));
    for (j=0;j<n;j++)
    {
        a[j] = rand()%40;
        cout<<a[j]<<" ";
    }
    clock_t start = clock();
    qsort(a,0,n-1);


    for (i=0;i<n;i++)
    {
        cout<<a[i]<<"  ";
    }
    cout<<"\nTime elapsed: "<<((double)clock() - start) / CLOCKS_PER_SEC<<endl;

}
4

0 回答 0