C 語言 qsort 排序 字符串數組
1
#include <stdio.h>
2
#include <stdlib.h>
3
#include <string.h>
4
5
#define N 100
6
#define L 100
7
8
int n;
9
char str[ N ][ L ];
10
11
int cmp( const void *a, const void *b ) {
12
return strcmp( ((const char*)a), ((const char*)b) );
13
}
14
15
int main() {
16
int i;
17
18
scanf( "%d", &n );
19
if ( 1 > n ) {
20
return 0;
21
}
22
for ( i = 0; i < n; ++i ) {
23
scanf( "%s", str[ i ] );
24
}
25
26
qsort( str, n, sizeof(str[ 0 ]), cmp );
27
28
printf( "\n\n" );
29
for ( i = 0; i < n; ++i ) {
30
printf( "%s\n", str[ i ] );
31
}
32
33
scanf( "%*c%*c" );
34
35
return 0;
36
}
37

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

qsort 其實不認識數據類型的,只認數組元素大小與內存布局,由自定義比較函數來做比較。
posted on 2011-10-27 23:08 coreBugZJ 閱讀(867) 評論(0) 編輯 收藏 引用 所屬分類: ProgrammingLanguage