快排算法C++模版

此算法为复习数据结构笔记

#include <iostream> 
#include <ctime>
using namespace std;

//
// 两值交换. 
//
template <typename T>
void swap1(T &x, T &y)
{
    T temp = x;
    x = y;
    y = temp;
}

//下标从0开始 
template <typename T>
int partition(T a[], int startIndex, int endIndex)
{//快速排序中的一趟 
	int i = startIndex;
	int j = endIndex;
	T key = a[startIndex];//作为枢轴来使用 
	while (i < j)
	{
		while(i < j && a[j] >= key)
			--j;
		swap1(a[i], a[j]);
		while(i < j && a[i] <= key)
			++i;
		swap1(a[j], a[i]);
		
	}
	a[i] = key;
	return i;

}

template <typename T>
void qsort(T a[], int startIndex, int endIndex)
{//快速排序的递归形式 
	int loc;
	if(startIndex < endIndex)
	{
		loc = partition(a, startIndex, endIndex);//一趟排序结果的调用 
		qsort(a, startIndex, loc-1);
		qsort(a, loc+1, endIndex);
	}

}

int main() 
{ 
    srand(unsigned(time(NULL)));//set 种子  
	int n =100;
    int a[100];  
    //产生随即数组  
    for(int i = 0; i < n; i++)  
    {  
//       a[i] = rand()%100;  
		a[i] = 100-i; 
    } 
    qsort(a, 0, n - 1); 
    for(int i = 0; i < n; i++) cout << a[i] << " "; 
    cout << endl; 

	return 0;
} 

  

posted @ 2013-05-29 11:56  盗草人  阅读(289)  评论(0编辑  收藏  举报