/*快速排序*/ /*quick_sort.h *使用第一个元素作为基准,左右交叉循环扫描 *假设数组有n个元素,则start = 0;end = n-1 */ #ifndef QUICK_SORTING_H #define QUICK_SORTING_H 1 template<typename T> void quickSort( T* m_array,int start,int end ) { int left=start; int right=end; T privotkey=m_array[ start ]; if( start<end ) { while( left<right ) { while( left<right && m_array[ right ]>privotkey ) //从右向左扫描 --right; m_array[ left ]=m_array[ right ]; //把小于privotkey的数移动到边 while( left<right && m_array[ left ]<=privotkey ) //从左向右扫描 ++left; m_array[ right ]=m_array[ left ]; //把大于privotkey的数移动到右边 } m_array[ left ]=privotkey; //此时有left==right quickSort( m_array,start,left-1 ); quickSort( m_array,left+1,end ); } } #endif /*test.cpp*/ #include "quick_sort.h" #include <iostream> using std::cout; using std::cin; using std::endl; int main( ) { int a [ ]={2,4,8,3,1,10}; cout<<"before the sorting/n"; for( int i=0;i<6;++i ) cout<<a[ i ]<<" "; cout<<endl; quickSort<int>( a,0,5); cout<<"after the sorting/n"; for( int i=0;i<6;++i ) cout<<a[ i ]<<" "; cout<<endl; return 0; }