快速排序 与 直接选择排序

/**************************************************************************
  * 题目:编写程序实现快速排序与直接选择排序相结合的排序算法。要求对输入
 *    的序列,用PARTITION过程分割成小于10个记录为一组的子序列,然后
 *    对每个子序列实施直接选择排序。
 * 函数:
 *    Swap: 交换两个参数的值
 *    Rand: 产生 begin至end之间的随机整数
 *    StraightSelectSort: 直接选择排序 
  *    PARTITION: 分区
 *    QUICKSORT: 实现排序
 *
  ***************************************************************************/

 #include <iostream>
 #include <iomanip>
 #include <time.h>
using namespace std;

 template < typename Type >
void inline Swap (Type& a, Type& b)
 {
     Type temp = a;
     a = b;
     b = temp;
 }

 template < typename Type >
 Type inline Rand (Type begin, Type end)
 {
     Type value = rand()%(begin - end + 1) + begin;             //value ~ [begin,end]
    return value;
 }

 template < typename Type >
void StraightSelectSort (Type list[], int begin, int end)
 {
     int min;
     for(int i=begin; i <= end; ++i)
     {
     min = i;
     for(int j=i; j <= end; ++j)
         if(list[j] < list[min])
         min = j;
     Swap<Type>(list[i],list[min]);
     }
 }

 template < typename Type >
int PARTITION (Type list[], int begin, int end)
 {
     int temp = Rand (begin ,end);
     Swap(list[temp],list[end]);

     int i = begin - 1;
     int x = list[end];
     for(int j = begin; j < end; ++j) // j: from begin to end-1
    {
     if(list[j] <= x)
     {
         ++i;
         Swap(list[i], list[j]);
     }
     }
     Swap(list[i+1], list[end]);
     return ++i;
 }

 template < typename Type >
void QUICKSORT ( Type list[], int begin, int end)
 {
     if(begin >= end)
     return;
     else if ( end - begin < 10 )
     StraightSelectSort (list, begin, end);
     else
     {
     int q = PARTITION (list, begin, end);
     QUICKSORT (list, begin, q-1);
     QUICKSORT (list, q, end);
     }
 }


//测试

int main()
 {
     srand(time(0));
     int x[100];
     for(int i=0;i<100;++i)
     x[i] = Rand(0, 1000); 

     cout << "随机生成的原始数据 :";
     for(int i=0;i<100;++i)
     {
     if(0 == i%10)
         cout<<endl;
     cout << setw(5) << x[i];
     }

     QUICKSORT (x, 0, 99);

     cout << endl << endl << "排序后的数据:";
     for(int i=0;i<100;++i)
     {
     if (0 == i%10)
         cout<<endl;
     cout << setw(5) << x[i]; 
     }
     return 0;
 }
原文地址:https://www.cnblogs.com/wc1903036673/p/3499665.html