使用qsort

   题目:编制程序,使用标准库函数qsort(),对各类数组进行排序;
  注:
  void qsort(void *,size_t nelem,size_t width,int(*fcmp)(const void *,const void *))
   (第一个参数是待排序数组,nelem是数组元素个数,width是元素类型的长度,fcmp是函数指针,比较两个参数,如果相等,
   则返回0,如果参数1大于参数2,则返回值正,否则返回值为负)

  (1)对整数数组进行排序,比较是以一个整数的各位数字之和的大小为依据,从小到大排列。数组中得元素为:
     12,32,42,51,8,16,51,21,19,9
  (2)对浮点数组进行排序。从小到大。数组中元素为
     32.1,456.87,332.67,442.0,98.12,451.79,340.12,54.55,99.87,72.5
  (3)对字符串数组进行排序,比较是以各字符串的长度为依据,如果相等,在比较字符串的值,从小到大排序。数组中得元素为:
     enter,number,size,begin,of,cat,case,program,certain,a

 

View Code
 1 #include <iostream>
2 #include <math.h>
3 #include <string.h>
4 #include <stdlib.h>
5
6 using namespace std;
7
8 int compare1(const void *a,const void *b)
9 {
10 int x=(*(int*)a/10)+(*(int*)a%10);
11 int y=(*(int*)b/10)+(*(int*)b%10);
12 if(x>y)
13 return 1;
14 if(x<y)
15 return -1;
16 else
17 return 0;
18
19 }
20
21 int compare2(const void *a,const void *b)
22 {
23 /* if(*(double*)a>*(double*)b)
24 return 1;
25 if(*(double*)a<*(double*)b)
26 return -1;
27 else
28 return 0; */
29 return ( *(double*)a - *(double*)b );
30
31 }
32
33 int compare3(const void *a,const void *b)
34 {
35 int len1=strlen((char*)a);
36 int len2=strlen((char*)b);
37 if(len1>len2)
38 return 1;
39 if(len1<len2)
40 return -1;
41 else
42 return strcmp((char *)a,(char*)b);
43 }
44
45 int main()
46 {
47 int a[]={12,32,42,51,8,16,51,21,19,9};
48 double b[]={32.1,456.87,332.67,442.0,98.12,451.79,340.12,54.55,99.87,72.5};
49 char c[10][8]={"enter","number","size","begin","of","cat","case","program","certain","a"};
50
51 cout<<endl;
52 qsort((void*)a,10,sizeof(int),compare1);
53 for(int i=0;i<10;i++)
54 cout<<a[i]<<"";
55 cout<<endl;
56
57 cout<<endl;
58 qsort((void*)b,10,sizeof(double),compare2);
59 for(i=0;i<10;i++)
60 cout<<b[i]<<"";
61 cout<<endl;
62
63 qsort((void*)c,10,sizeof(c[0]),compare3);
64 for(i=0;i<10;i++)
65 cout<<c[i]<<"";
66 cout<<endl;
67
68 return 0;
69 }

 

转载于:https://www.cnblogs.com/2011-9-13/archive/2011/11/13/2247349.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值