C 语言快速排序算法以及 qsort

 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 int comp(const void *a, const void *b){
22   float x = *(float *)a;
23   float y = *(float *)b;
24 
25   if( x > y ) return 1;
26   else if( x < y ) return -1;
27   else return 0;
28 }
29 
30 int main(int argc, char *argv[]){
31   float data[10], data1[10];
32   int i = 0;
33   srand((unsigned)time(NULL));
34 
35   printf("\n sort data: ");
36   for(i = 0; i < 10; i++){//生成随机数
37     data[i] = rand() % 100  * 0.1;
38     data1[i] = data[i];
39     printf("[%.1f] ",data[i]);
40   }
41   
42   quick_sort(data,0, 9);
43   qsort(data1, 10, sizeof(float), comp);
44 
45   printf("\nquick_sort: ");
46   for(i = 0; i < 10; i++) printf("[%.1f] ", data[i]);
47 
48   printf("\nlib  qsort: ");
49   for(i = 0; i < 10; i++) printf("[%.1f] ", data1[i]);
50   printf("\n");
51 
52   return 0;
53 }

运行结果

         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]

上一篇:HTML5新特性学习-2


下一篇:Apache中压力测试工具ab的操作说明