- UID
- 44482
注册时间2008-2-7
阅读权限20
最后登录1970-1-1
以武会友
该用户从未签到
|
发表于 2009-7-29 22:19:52
|
显示全部楼层
很像the c++ programming language上的例题。- #include <string.h>
- #include <iostream>
- using namespace std;
- typedef int (*CFT)(const void*, const void*);
- struct User
- {
- char* name;
- char* id;
- int dept;
- };
- /*
- 字符串比较
- */
- int str_cmp(const void* p, const void* q)
- {
- return strcmp(static_cast<const User*>(p)->name,static_cast<const User*>(q)->name);
- }
- /*
- 数值比较
- */
- int int_cmp(const void* p, const void* q)
- {
- return static_cast<const User*>(p)->dept - static_cast<const User*>(q)->dept;
- }
- /*
- 对向量base的n个元素按照递增顺序排序,
- 用由"cmp"所指定的函数做比较,
- 元素大小是"sz".
- */
- void ssort(void* base, size_t n, size_t sz, CFT cmp)
- {
- for(int gap = n/2; 0 < gap; gap /= 2)
- for (int i = gap; i < n; i++)
- for (int j = i-gap; 0 <= j; j -= gap)
- {
- char* b = static_cast<char*>(base);
- char* pj = b + j*sz; //&base[j]
- char* pjg = b + (j + gap) * sz; //&base[j+gap]
- if (cmp(pjg,pj) < 0)
- {
- for (int k = 0; k < sz; k++)
- {//swap base[j],base[j+gap]
- char temp = pj[k];
- pj[k] = pjg[k];
- pjg[k] = temp;
- }
- }
- }
- }
- /*
- 输出函数
- v 是结构体User数组首地址,
- n 是数组元素个数
- */
- void print_id(User* v, int n)
- {
- for (int i = 0; i < n; i++)
- cout << v[i].name << '\t' << v[i].id << '\t' << v[i].dept << '\n';
- }
- User heads[] =
- {
- "kevin", "t1", 1,
- "Neo", "t3", 3,
- "Eric", "t2", 2
- };
- int main(int argc, char* argv[])
- {
- cout << "Heads in alphabetical order:\n";
- ssort(heads,3,sizeof(User),str_cmp);
- print_id(heads, 3);
- cout << '\n';
- cout << "Heads in order of department number:\n";
- ssort(heads, 3, sizeof(User), int_cmp);
- print_id(heads,3);
- return 0;
- }
复制代码 |
|