排序——快速排序(三数取中法和优化不必要交换)
#include <iostream> #include <stdlib.h> using namespace std; #define MAXSIZE 10 void swap(int k[], int low,int high) { int temp; temp = k[low]; k[low] = k[high]; k[high] = temp; } int Partition(int k[], int low, int high) { int point; int m = low + (high - low)/2; if(k[low] > k[high]) { swap(k, low ,high); } if(k[m] > k[high]) { swap(k, m ,high); } if(k[m] > k[low]) // 使得low存放中间的值 { swap(k, m, low); } point = k[low]; while(low < high) { while( low < high && k[high] >= point ) //过滤掉比low大的 { high--; }//出了循环说明要进行移动 k[low] = k[high]; while( low < high && k[low] <= point ) { low++; } //出了循环说明左边大于右边 要进行移动 k[high] = k[low]; } k[low] = point; return low; } void QSort(int k[], int low, int high) { int point; if( low < high ) { point = Partition(k , low , high); QSort(k, low,point-1); //左边 QSort(k, point+1, high); // 右边 } } void QuickSort( int k[], int n ) { QSort( k, 0, n-1 ); } int main() { int i ,a[10] = {5,2,6,0,3,9,1,7,4,8}; QuickSort(a,10); for( i=0; i < 10 ;i++ ) { cout << a[i]; } cout << endl; return 0; }
作者: kent鹏
出处: http://www.cnblogs.com/xieyupeng/
关于作者:专注JAVAEE领域,请多多赐教!
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。