Posted on 2014-07-19 12:27
xLsDg 阅读(225)
评论(0) 编辑 收藏 引用 所属分类:
代码库
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 void bubbleSort( int data[], int n )
5 {
6 int i, j, flag = 1, run = 0, swap = 0;
7
8 for ( i = 0; i < n && flag; i++ ) {
9 for ( j = 0, flag = 0; j < n - i - 1; j++ ) {
10 if ( data[j] > data[j + 1] ) {
11 printf( "%d --> %d\n", data[j], data[j + 1] );
12 flag = 1;
13 data[j] ^= data[j + 1];
14 data[j + 1] ^= data[j];
15 data[j] ^= data[j + 1];
16 swap++;
17 }
18 run++;
19 }
20 }
21
22 printf( "[run=%d, swap=%d]\n", run, swap );
23 }
24
25 void printData( int data[], int n )
26 {
27 int i;
28
29 for ( i = 0; i < n; i++ ) {
30 printf( "%d ", data[i] );
31 }
32
33 printf("\n");
34 }
35
36 int main( int argc, const char *argv )
37 {
38 int data1[] = { 7, 4, 1, 0, 8, 5, 2, 9, 6, 3 };
39 int data2[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
40 int data3[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
41
42 int dataLen = sizeof( data1 ) / sizeof( data1[0] );
43
44 printData( data1, dataLen );
45 bubbleSort( data1, dataLen );
46 printData( data1, dataLen );
47 printf("\n");
48
49 printData( data2, dataLen );
50 bubbleSort( data2, dataLen );
51 printData( data2, dataLen );
52 printf("\n");
53
54 printData( data3, dataLen );
55 bubbleSort( data3, dataLen );
56 printData( data3, dataLen );
57 printf("\n");
58
59 return 0;
60 }
61