更新时间:2022-06-22 08:45:48
引言:通过参考c语言库函数qsort:
1
|
void qsort ( void *base, size_t num, size_t width, int (__cdecl *compare )( const void *elem1, const void *elem2 ) );
|
完成回调函数实现冒泡排序字符串或数字:
代码如下:
1
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
#include <stdio.h> #include <stdlib.h> #include <string.h> /* 函数功能:以char类型交换两个元素,大小为size。 */ void swap( char *p1, char *p2, int size)
{ int i = 0;
char tmp = 0;
for (i = 0;i<size;i++)
{
tmp = *(p1+i);
*(p1+i) = *(p2+i);
*(p2+i) = tmp;
}
} /* 函数功能:比较整数的回调函数。 */ int compare_int( const void *elem1, const void *elem2)
{ return (*( int *)elem1) - (*( int *)elem2);
} /* 函数功能:比较字符串的回调函数。 */ int compare_str( const void *elem1, const void *elem2)
{ return strcmp (( char *)(*( int *)elem1), ( char *)(*( int *)elem2));
} /* 函数功能:冒泡排序函数。 */ void bubble_str_int( void *base, int size, int width, int ( *cmp )( const void *elem1, const void *elem2 ))
{ int i = 0;
int j = 0;
for (i = 0;i<size-1;i++)
{
for (j = 0;j<size-i-1;j++)
{
if (cmp((( char *)base+(j*width)),(( char *)base+(j+1)*width))<0)
{
swap(( char *)base+(j*width),( char *)base+(j+1)*width,width);
}
}
}
} int main()
{ char *arr_str[] = { "ddddd" , "aaaaa" , "ccccc" , "bbbbb" , "zzzzz" };
int arr_int[] = {1,3,5,7,9,2,4,6,8,10};
int i = 0;
int size_int = sizeof (arr_int)/ sizeof (arr_int[0]);
int size_str = sizeof (arr_str)/ sizeof (arr_str[0]);
bubble_str_int(arr_int,size_int, sizeof (arr_int[0]),compare_int);
printf ( "bubble_sort int:\n" );
for (i = 0;i<size_int;i++)
{
printf ( "%d " ,arr_int[i]);
}
printf ( "\n" );
bubble_str_int(arr_str,size_str, sizeof (arr_str[0]),compare_str);
printf ( "bubble_sort string:\n" );
for (i = 0;i<size_str;i++)
{
printf ( "%s\n" ,arr_str[i]);
}
system ( "pause" );
return 0;
} |
注:主要思想:排序的是什么元素都将其强制类型转换成(char*),因为可以把char当作一个基类。然后再根据排序元素的类型,将其强制类型转化成目标类型.
例如:
1
2
3
4
|
int compare_int( const void *elem1, const void *elem2)
{ return (*( int *)elem1) - (*( int *)elem2);
} |
把基类强制类型转换成int*再*就得到int类型的数据。compare_int函数也是如此。
本文转自 8yi少女的夢 51CTO博客,原文链接:http://blog.51cto.com/zhaoxiaohu/1720540,如需转载请自行联系原作者