快速排序是在实践中最快的已知排序算法,它的平均运行时间是O(NlogN)。该算法之所以特别快,主要是由于非常精炼和高度优化的内部循环。
编码实现如下:
#include <iostream>
#include <vector>
using namespace std;
template <typename Comparable>
void insertionSort( vector<Comparable> &a,int left,int right )
{
int j;
for ( int p = left + 1 ; p < right + 1 ; p++ ){
Comparable tmp = a[p]; //保存当前元素值
for ( j = p ; j > left && tmp < a[j - 1] ; j-- ) //通过循环将位置p之前比p大的元素都向右移一格
a[j] = a[j - 1];
a[j] = tmp; //最后在适当的位置插入元素值.
}
}
template <typename Comparable>
const Comparable &median3( vector<Comparable> &a,int left,int right )
{
int center = ( left + right ) / 2;
if ( a[center] < a[left] )
swap( a[left],a[center] );
if ( a[right] < a[left] )
swap( a[left],a[right] );
if ( a[right] < a[center] )
swap( a[center],a[right] );
swap( a[center],a[right - 1] );
return a[right - 1];
}
template <typename Comparable>
void quicksort( vector<Comparable> &a,int left,int right )
{
if ( left + 10 <= right ){
Comparable pivot = median3( a,left,right );
int i = left,j = right - 1;
for ( ; ; ){
while( a[++i] < pivot ) {}
while ( pivot < a[--j] ) {}
if ( i < j )
swap( a[i],a[j] );
else
break;
}
swap( a[i],a[right - 1] );
quicksort( a,left,i - 1 );
quicksort( a,i + i,right );
}
else
insertionSort( a,left,right );
}
template <typename Comparable>
void quicksort( vector<Comparable> &a )
{
quicksort( a,0,a.size() - 1 );
}
int main()
{
cout << "请输入一些数据:" << endl;
vector<int> vec;
int temp;
while ( cin >> temp )
vec.push_back( temp );
quicksort( vec );
cout << "按升序排列过的数据如下:" << endl;
vector<int>::iterator iter = vec.begin();
while( iter != vec.end() )
cout << *iter++ << endl;
return 0;
}