选择排序--写起来简单多了:

 

 
  
  1. #include <iostream>  
  2. #include <stdlib.h>  
  3. #include <time.h>  
  4.  
  5. using namespace std;  
  6.  
  7. int g_nCases = 0;  
  8.  
  9. template<class T>  
  10. void SelectedSort(T array[], int n)  
  11. {  
  12.     int nMiniIndex;  
  13.     for(int i=0; i<n; i++){  
  14.          nMiniIndex = i;  
  15.          for(int j=i+1; j<n; j++){  
  16.               if(array[nMiniIndex]>array[j]){  
  17.                    nMiniIndex = j;  
  18.               }  
  19.          }  
  20.          if(nMiniIndex!=i){  
  21.               swap(array[nMiniIndex], array[i]);      
  22.          }     
  23.     }  
  24. }  
  25.  
  26. template<class T>  
  27. void  printArray(T array[], int n)  
  28. {  
  29.       cout<<"Case "<<g_nCases++<<" :"<<endl;  
  30.       for(int i=0; i<n; i++)  
  31.           cout<<array[i]<<", ";  
  32.       cout<<endl;     
  33. }  
  34.  
  35. int main(int argc, char *argv[])  
  36. {  
  37.     srand((unsigned)time(NULL));  
  38.       
  39.     const int N = 1000;  
  40.     int array[N];  
  41.     // Init  
  42.     for(int i=0; i<N; i++){  
  43.         array[i] = rand()%N;      
  44.     }  
  45.       
  46.     printArray(array, N);  
  47.     SelectedSort(array, N);  
  48.     printArray(array, N);  
  49.     return 0;