quick_sort

Average-case running time: O(nlgn)
Worst-case running time: O(n^2)

There is also randomized version of quick_sort

The original partition algorithm is hoare_partition

 

 

代码
/////////////////////Test Code/////////////////////
#include "stdafx.h"
#include
"stdlib.h"
#include
<time.h>
#include
"basic_algorithm.h"
#include
<iostream>
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{

srand((unsigned)time(NULL));
int *arr = new int[20];
for(int i = 0; i < 20; ++i)
{
arr[i]
= rand() % 30;
}
enzo::quick_sort(arr,
20);
for(int i = 0; i < 20; ++i)
{
cout
<< arr[i] << " ";
}
cout
<< endl;
system(
"pause");
return 0;
}

//////////////////Source Code//////////////////////
template<typename _T>
int partition(_T *arr, int from, int to)
{
int j = from;
int k = from;
_T temp
= arr[to];
while(k < to)
{
if(arr[k] < temp)
{
ez_swap(arr[j],arr[k]);
++j;
++k;
}
else
{
++k;
}
}
if(arr[to] < arr[j])
{
ez_swap(arr[to], arr[j]);
}
return j;
}
template
<typename _T>
void quick_sort(_T *arr, int from, int to)
{
if(from < to)
{
int mid = partition(arr, from, to);
quick_sort(arr, from, mid
- 1);
quick_sort(arr, mid
+ 1, to);
}
}

template
<typename _T>
void quick_sort(_T *arr, int n)
{
quick_sort(arr,
0, n-1);
}

 

posted @ 2010-04-29 21:24  Yang Enzo  阅读(152)  评论(0编辑  收藏  举报