0001 0002 /****************************************************************************************** 0003 * 构造随机数组(可根据测试需要相应地改写) 0004 ******************************************************************************************/ 0005 void randomArray ( int A[], int n, int seed ) { 0006 srand ( seed ); 0007 for ( int i = 0; i < n; i++ ) A[i] = i; 0008 shuffle ( A, 0, n / 3 ); 0009 shuffle ( A, 2 * n / 3, n ); 0010 } 0011 0012 /****************************************************************************************** 0013 * 起泡排序测试程序 0014 ******************************************************************************************/ 0015 void main ( int argc, char* argv[] ) { 0016 int n = 0; //array length 0017 if ( 1 < argc ) n = atoi ( argv[1] ); if ( n < 0 ) n = 0; //make sure length is non-negative 0018 int* A = ( int* ) malloc ( n * sizeof ( int ) ); //allocate an array of size n 0019 unsigned int seed = ( unsigned int ) time ( NULL ); //A same seed is used here for comparison between different algorithms 0020 printf ( "\n== Bubblesort algorithm #0 ========\n" ); 0021 randomArray ( A, n, seed ); //create a randomized array using the same seed 0022 printf ( "--> " ); print ( A, n ); 0023 bubblesort ( A, n ); //sort the array using algorithm#0 0024 printf ( "==> " ); print ( A, n ); 0025 printf ( "\n== Bubblesort algorithm #1A ========\n" ); 0026 randomArray ( A, n, seed ); //create a randomized array using the same seed 0027 printf ( "==> " ); print ( A, n ); 0028 bubblesort1A ( A, n ); //sort the array using algorithm#1A 0029 printf ( "==> " ); print ( A, n ); 0030 printf ( "\n== Bubblesort algorithm #1B ========\n" ); 0031 randomArray ( A, n, seed ); //create a randomized array using the same seed 0032 printf ( "==> " ); print ( A, n ); 0033 bubblesort1B ( A, n ); //sort the array using algorithm#1B 0034 printf ( "==> " ); print ( A, n ); 0035 printf ( "\n== Bubblesort algorithm #2 ========\n" ); 0036 randomArray ( A, n, seed ); //create a randomized array using the same seed 0037 printf ( "==> " ); print ( A, n ); 0038 bubblesort2 ( A, n ); //sort the array using algorithm#2 0039 printf ( "==> " ); print ( A, n ); 0040 free ( A ); //release the array 0041 }