快速排序(quick sort):通过一趟排序将要排序的数据分割成独立的两个部分,其中一个部分的所以数据都比另外一部分的所有数据都要小。
时间复杂度:O(nlgn)
实例:(边界值,选择数组的第一个元素作为边界值)
<pre name="code" class="cpp">#include "stdafx.h"
#include <iostream>
using namespace std;
template<class T>
void QuickSort(T data[], const int left, const int right)
{
if (left >= right)
return;
int low = left;
int hight = right;
int key = data[low];
while (low < hight)
{
while (low < hight && data[hight] >= key)
{
--hight;
}
data[low] = data[hight];
while (low < hight && data[low] <= key)
{
++low;
}
data[hight] = data[low];
}
data[low] = key;
QuickSort(data, left, low);
QuickSort(data, low + 1, right);
}
template<class T>
void Sprint(T data[], int n)
{
for (int i = 0; i < n; i++)
{
cout << data[i] << " ";
}
cout << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
int data[] = { 0, 3, 5, 1, 4, 6, 2 ,11 };
int n = sizeof(data) / sizeof(int);
QuickSort(data, 0, n - 1);
Sprint(data, n);
return 0;
}