排序——快速排序(三数取中法和优化不必要交换)

#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;
}

 

posted @ 2017-06-19 10:01  kent鹏  阅读(2348)  评论(0编辑  收藏  举报