c 语言冒泡排序与快速排序示例:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <time.h> 4 //快速排序 5 void quick_sort(float data[], int left, int right){ 6 int i = left; 7 int j = right; 8 float tag = data[i]; 9 while(i<j){ 10 while( i<j && tag < data[j] ) j--; 11 if( i<j ) data[i++] = data[j]; 12 13 while( i<j && tag > data[i] ) i++; 14 if( i<j ) data[j--] = data[i]; 15 } 16 data[i] = tag; 17 if( left < i ) quick_sort(data, left, j - 1); 18 if( i < right ) quick_sort(data, j + 1, right); 19 } 20 //冒泡排序 21 void bub_sort(float data[], int n){ 22 int i,j; 23 float tmp; 24 for( i = 0; i < n - 1; i++ ) 25 for( j = 0; j < n - 1 - i; j++) 26 if(data[j] > data[j + 1]) 27 { 28 tmp = data[j]; 29 data[j] = data[j + 1]; 30 data[j + 1] = tmp; 31 } 32 } 33 //比较函数 34 int comp(const void *a, const void *b){ 35 float x = *(float *)a; 36 float y = *(float *)b; 37 38 if( x > y ) return 1; 39 else if( x < y ) return -1; 40 else return 0; 41 } 42 43 int main(int argc, char *argv[]){ 44 float data[10], data1[10]; 45 int i = 0; 46 srand((unsigned)time(NULL)); 47 48 printf(" sort data: "); 49 for(i = 0; i < 10; i++){//生成随机数 50 data[i] = rand() % 100 * 0.1; 51 data1[i] = data[i]; 52 printf("[%.1f] ",data[i]); 53 } 54 55 quick_sort(data,0, 9); 56 qsort(data1, 10, sizeof(float), comp); 57 58 printf(" quick_sort: "); 59 for(i = 0; i < 10; i++) printf("[%.1f] ", data[i]); 60 61 printf(" lib qsort: "); 62 for(i = 0; i < 10; i++) printf("[%.1f] ", data1[i]); 63 printf(" "); 64 65 return 0; 66 }
运行结果
sort data: [8.6] [1.2] [5.1] [8.3] [6.5] [4.8] [5.3] [5.3] [7.3] [3.6]
quick_sort: [1.2] [3.6] [4.8] [5.1] [5.3] [5.3] [6.5] [7.3] [8.3] [8.6]
lib qsort: [1.2] [3.6] [4.8] [5.1] [5.3] [5.3] [6.5] [7.3] [8.3] [8.6]