数组快速排序
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_ARRY 10
#define SWAP(x,y) ({int t;t= x;x= y;y=t;})
static void arry_print( int arry[] , int size_of_element );
static void quicksort2( int arry[] , int left , int right );
static void quicksort1( int number[],int left, int right );
int main(int argc, char const *argv[])
{
int arry[MAX_ARRY] = {0};
int i,j;
srand(time(NULL));
for ( i =0 ; i < MAX_ARRY ; i++ )
arry[i] = rand() % 100;
printf("bofore sort:\n");
arry_print( arry, MAX_ARRY );
quicksort1( arry , 0, MAX_ARRY ); //1.411 12.89 13.96
//quicksort2( arry , 0, MAX_ARRY ); //1.568 13.06 13.41
printf("after sort:\n");
arry_print( arry, MAX_ARRY );
return 0;
}
static void quicksort1( int number[],int left,int right)
{
int i,j,s;
if( left < right )
{
s = number[left];
i = left;
j = right+ 1;
while(1)
{
// 向右找,直到找到比轴心 s 大的数字
while(i + 1 < MAX_ARRY && number[++i] < s);
// 向左找,直到找到比轴心 s 小的数字
while(j -1 > -1 && number[--j] > s);
if(i >= j )
break;
SWAP( number[i], number[j] );
}
number[left] = number[j]; // 从新设定轴心
number[j] = s;
quicksort1( number, left, j-1); // 对左边进行递回
quicksort1( number, j+1, right); // 对右边进行递回
}
return ;
}
static void quicksort2( int arry[] , int left , int right )
{
int i;
int j;
int s;
if ( left < right )
{
i = left - 1 ;
j = right + 1;
s = arry[(right+left)/2];
while ( 1 )
{
while ( arry[++i] < s ) ;
while ( arry[--j] > s ) ;
if ( i >= j ) break;
SWAP( arry[i] , arry[j] );
}
quicksort2( arry , left , i -1 );
quicksort2( arry , j + 1 , right );
}
return ;
}
static void arry_print( int arry[] , int size_of_element )
{
int i = 0;
while ( i < size_of_element )
printf("%d ", arry[i++]);
printf("\n");
return ;
}
结果如下: