[原]键盘输入5个用户的数据,包括:姓名和电话号码要求按姓名排序
//3. 从键盘输入5个用户的数据,包括:姓名和电话号码// 要求按姓名排序后,输出用户的全部数据。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 5
typedef struct Person
{
char szName ;
char szNumber ;
}person ;
int compare(const void * elem1, const void * elem2)
{
return strcmp(((person *)elem1)->szName, ((person *)elem2)->szName) ;
}
int main(void)
{
int i ;
person p ;
for (i = 0; i < MAX; ++i)
{
scanf("%20s%20s", &p.szName, &p.szNumber) ;
}
qsort(&p, MAX, sizeof(person), compare) ;
for (i = 0; i < MAX; ++i)
{
printf("%22s%22s\r\n", p.szName, p.szNumber) ;
}
return 0 ;
} 很像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
char* pjg = b + (j + gap) * sz; //&base
if (cmp(pjg,pj) < 0)
{
for (int k = 0; k < sz; k++)
{//swapbase,base
char temp = pj;
pj = pjg;
pjg = temp;
}
}
}
}
/*
输出函数
v 是结构体User数组首地址,
n 是数组元素个数
*/
void print_id(User* v, int n)
{
for (int i = 0; i < n; i++)
cout << v.name << '\t' << v.id << '\t' << v.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;
}
页:
[1]