c语言----qsort使用

 1 //------------------------------------------
 2 //      c语言 qsort 测试 
 3 //函数原型:
 4 //_ACRTIMP void __cdecl qsort(
 5 //_Inout_updates_bytes_(_NumOfElements * _SizeOfElements) void*  _Base,
 6 //_In_                                                    size_t _NumOfElements,
 7 //_In_                                                    size_t _SizeOfElements,
 8 //_In_                _CoreCrtNonSecureSearchSortCompareFunction _CompareFunction
 9 //);
10 //
11 //参数介绍:
12 //  参数1: 要排序内容的基地址,其中的内容会被交换,内容可以是数据内容,也可是指针地址,
13 //  参数2: 要排序的内容的数量
14 //  参数3: 交换数据的单位,每次比较结果得到以后以该单位进行值的交换
15 //  参数4: 比较函数,其中的比较可以是你排序内容直接比较的结果,也可以是其指针内的某一小块内容比较的结果
16 //
17 //eg: 对 整数 数组 进行排序 【两种实现】
18 //   
19 //  1. 交换数字的值,实现排序
20 //
21 //  2. 交换指针的值,实现排序
22 //-------------------------------------------
23 #include "gtest/gtest.h"
24 #include <iostream>
25 using namespace std;
26 
27 int com_qsort_1(const void *a, const void *b)
28 {
29     int *tem1 = (int*)a;
30     int *tem2 = (int*)b;
31     return *tem1 > *tem2;
32 }
33 
34 int com_qsort_2(const void *a, const void *b)
35 {
36     int **tem1 = (int**)a;
37     int **tem2 = (int**)b;
38     return *(*tem1) > *(*tem2);
39 }
40 
41 // @lc code=end
42 
43 TEST(add_mult, test001)
44 {
45     int a1[5] = { 8, 3, 9, 7, 6 };
46     int a2[5] = { 8, 3, 9, 7, 6 };
47     int *pa2[5];
48     int tem = 5;
49     for (int i = 0;i < tem;i++) {
50         pa2[i] = &a2[i];
51     }
52     qsort(a1, tem, sizeof(int), com_qsort_1);
53     qsort(pa2, tem, sizeof(int*), com_qsort_2);
54 
55     for (int i = 0;i < tem;i++) {
56         cout << a1[i] << "  " << *pa2[i] << endl;
57     }
58 }

posted @ 2020-03-26 20:38  博客园—哆啦A梦  阅读(352)  评论(0)    收藏  举报