C/C++: 排序

C/C++: 排序
#include  < iostream >
#include 
< ctime >
#include 
< cmath >

void  quickSort( int   * array,  int  first,  int  last) {
    
if  (first  >=  last) {
        
return ;
    }
    
    
int  referenceValue  =  array[(first  +  last)  /   2 ];
    
int  i  =  first;
    
int  j  =  last;
    
    
while  (i  <=  j) {
        
while  (i  <=  last  &&  array[i]  <  referenceValue) {
            
++ i;
        }
        
while  (j  >=  first  &&  array[j]  >  referenceValue) {
            
-- j;
        }
        
        
if  (i  <=  j) {
            
int  temp  =  array[i];
            array[i] 
=  array[j];
            array[j] 
=  temp;
            
            
++ i;
            
-- j;
        }
    }
    
    quickSort(array, first, j);
    quickSort(array, i, last);
}

void  selectSort( int   * array,  int  length) {
    
for  ( int  i  =   0 ; i  <  length  -   1 ++ i) {
        
for  ( int  k  =  i  +   1 ; k  <  length;  ++ k) {
            
if  (array[k]  <  array[i]) {
                
int  temp  =  array[i];
                array[i] 
=  array[k];
                array[k] 
=  temp;
            }
        }
    }
}

void  sort( int   * array,  int  length) {
    
if  (length  <   30 ) {
        selectSort(array, length);
    } 
else  {
        quickSort(array, 
0 , length  -   1 );
    }
}

int  main() {
    srand(time(
0 ));
    
int  length  =   0 ;
    
    
for  ( int  count  =   0 ; count  <   20 ++ count) {
        length 
=  rand()  %   50 ;
        
int   * array  =   new   int [length];
        
for  ( int  i  =   0 ; i  <  length;  ++ i) {
            
* (array  +  i)  =  rand()  %   500 ;
        }
        
        sort(array, length);
        
        
for  ( int  i  =   0 ; i  <  length;  ++ i) {
            std::cout 
<<  array[i]  <<   " " ;
        }
        
        delete[] array;
        
        std::cout 
<<  std::endl;
    }
    
    
return   0 ;
}


你可能感兴趣的:(C/C++: 排序)