QuickSort

 
// main.cpp
// QuickSort

#include
"stdafx.h"
#include
<iostream>
#include
<iterator>
#include
<algorithm>
using namespace std ;

#define EXCHAGE(X, Y) ((X) != (Y) ? (X) ^= (Y) ^= (X) ^= (Y) : NULL)

int Partition(int arr[], int start, int end)
{
int i = start-1, j = start ;

for (;j < end ;++j)
{
if (arr[j] <= arr[end])
{
// Swap two build-in type variable
++i ;
EXCHAGE(arr[i], arr[j]) ;
}
//if
}//for

++i ;
EXCHAGE(arr[i], arr[j]) ;

return i ;
}

void QuickSort(int arr[], int begin, int end)
{
if (begin < end)
{
int mid = Partition(arr, begin, end) ;
QuickSort(arr, begin, mid
-1) ; // Left hand
QuickSort(arr, mid+1, end) ; // Right hand
}//if
}

int main()
{
int arr[] = {2, 8, 7, 1, 3, 5, 6, 4} ;

QuickSort(arr,
0, sizeof(arr)/sizeof(arr[0]) - 1) ;

copy(arr, arr
+ sizeof(arr)/sizeof(arr[0]), ostream_iterator<int>(cout, " ")) ;

return 0;
}

  快排是一种不稳定排序, 其最差时间复杂度是 n^2. 但快排是通常排序的最佳实践选择. 因为其平均期望运行时间是 nlog(n).

posted @ 2011-04-27 10:46  walfud  阅读(332)  评论(1编辑  收藏  举报