C++代码实现快速排序

时间:2014-04-27 22:15:20   收藏:0   阅读:361
#include <iostream>
using namespace std;
// quick sort  
//另外,如果数组是引用传递可以通过函数模板的实参推断来自动获得它长度
template<typename T,int N> 
void printArr(T (&arr)[N])
{
   int i = 0;  
   while(i<N)
   {
	   cout << arr[i] <<" ";
	   i++;
   }
   cout <<endl;
}

void swap(int &p,int &q)
{
	int temp = p;
	p= q;
	q=temp;
}
int getIndex(int arr[],int nLow,int nHigh)
{
	int nTemp = arr[nHigh];
	int j = nLow - 1;
	for(int i=nLow;i<nHigh;i++)
	{
		if ( arr[i] <= nTemp) 
		{
            j=j+1;
			swap(arr[j],arr[i]);
		}
	}
	swap(arr[j+1],arr[nHigh]);
	return j+1;
}



void quickSort(int arr[],int nLow,int nHigh)
{
	if (nLow < nHigh)
	{
		int nIndex = getIndex(arr,nLow,nHigh);
		quickSort(arr,nLow,nIndex-1);
		quickSort(arr,nIndex + 1,nHigh);
		
	}
}

int main()
{

#ifdef __cplusplus
	cout <<"c++" <<endl;
#else
	cout <<"c " <<endl;
#endif
	int arr[] = {52,49,80,36,14,75,58,56,57,78,42,22,22,44};
    
	
	quickSort(arr,0,sizeof(arr)/sizeof(arr[0]));

	printArr(arr);

	return 0;
}

http://www.cnblogs.com/pugang/archive/2012/06/27/2565093.html

具体逻辑见上面的链接

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!