forked from SilverMaple/STLSourceCodeNote
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1_9_6_qsort.cpp
More file actions
41 lines (33 loc) · 924 Bytes
/
1_9_6_qsort.cpp
File metadata and controls
41 lines (33 loc) · 924 Bytes
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
// file: 1qsort.cpp
// c++使用函数对象/仿函数实现一组动作
// c使用函数指针实现一组动作,但是无法存储状态在里面
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int fcmp(const void *elem1, const void *elem2);
int main() {
int ia[10];
// int ia[10] = {32, 92, 67, 58, 10, 4, 25, 52, 59, 54};
srand((unsigned int)time(NULL));
for (int i = 0; i < 10; i++) {
ia[i] = rand() % 100 + 1;
cout << ia[i] << " ";
}
cout << endl;
// 快速排序
qsort(ia, sizeof(ia) / sizeof(int), sizeof(int), fcmp);
for (int i = 0; i < 10; i++) {
cout << ia[i] << " ";
}
}
int fcmp(const void* elem1, const void* elem2) {
const int *i1 = (const int *)elem1;
const int *i2 = (const int *)elem2;
if (*i1 < *i2)
return -1;
else if (*i1 == *i2)
return 0;
else
return 1;
}