您的位置:首页 > 编程语言 > C语言/C++

c语言中使用自带的qsort(结构体排序)+ 快排

2018-11-20 11:15 543 查看

c语言中使用自带的qsort(结构体排序)+ 快排

c中没有自带的sort函数emm

不过有自带的qsort函数

(其实用法都差不多(只是我经常以为c中有sort

头文件要用

 1 #include <stdlib.h> 

一定要重新把指针指向的值赋值给一个node类型,不然比较不了

1 struct node{
2     int d,id,tmp;
3 }a
;
4
5 int cmp(const void *x,const void *y){
6     struct node xx = *(struct node*)x;
7     struct node yy = *(struct node*)y;
8     return xx.d-yy.d;
9 }
10
11 qsort(a+1,n,sizeof(a[1]),cmp);//调用 排序a[1]~a[1+n]

这里贴一个代码,实现的功能是给定一个数组(数组中每个数不一样),然后输入一些数,问你这些数在数组中的位置(从0开始编号)

(其实是我看错题的产物(写都写了(就是实现一下离散化而已,当个小例子看吧

1 #include <stdio.h>
2 #include <string.h>
3 #include <stdlib.h>
4
5 #define N 2*100010
6
7 struct node{
8     int d,id,tmp;
9 }a
;
10 int b
,q
,ans
;
11
12 int cmp(const void *x,const void *y){
13     struct node xx = *(struct node*)x;
14     struct node yy = *(struct node*)y;
15     return xx.d-yy.d;
16 }
17
18 int  main()
19 {
20     //freopen("a.in","r",stdin);
21     int n,m;
22     scanf("%d",&n);
23     for(int i=1;i<=n;i++)
24     {
25         scanf("%d",&a[i].d);
26         a[i].id=i;
27         a[i].tmp=0;
28     }
29     scanf("%d",&m);
30     for(int i=1;i<=m;i++)
31     {
32         scanf("%d",&q[i]);
33         a[n+i].d=q[i];
34         a[n+i].id=i;
35         a[n+i].tmp=1;
36     }
37     qsort(a+1,n+m,sizeof(a[1]),cmp);
38     int now=0,p=0;
39     for(int i=1;i<=n+m;i++)
40     {
41         if(i==1 || a[i].d!=p) now++;
42         p=a[i].d;a[i].d=now;
43         if(a[i].tmp==0) b[now]=a[i].id;
44     }
45     for(int i=1;i<=n+m;i++)
46     {
47         if(a[i].tmp==1) ans[a[i].id]=b[a[i].d];
48     }
49     for(int i=1;i<=m;i++)
50         printf("%d\n",ans[i]-1);
51     return 0;
52 }

 

还写了一个纯排序的代码,非结构体的。手写快排,或者用系统自带qsort

1 #include<stdio.h>
2 #include<string.h>
3 #include<stdlib.h>
4
5 int n,a[100010];
6 void quicksort(int a[],int l,int r)
7 {
8     int i=l,j=r,key=a[l];
9     if(l>=r)return;
10     while(i!=j)
11     {
12         while(i<j && a[j]>=key) j--;
13         a[i]=a[j];
14         while(i<j && a[i]<=key) i++;
15         a[j]=a[i];
16     }
17     a[i]=key;
18     quicksort(a,l,i-1);
19     quicksort(a,i+1,r);
20 }
21
22
23 int cmp(const void *x,const void *y){
24     // int xx=*(int *)x;
25     // int yy=*(int *)y;
26     // return xx-yy;
27     return *(int *)x-*(int *)y;
28 }
29
30 int main()
31 {
32     // freopen("a.in","r",stdin);
33     // freopen("a.out","w",stdout);
34     scanf("%d",&n);
35     for(int i=1;i<=n;i++) scanf("%d",&a[i]);
36     // quicksort(a,1,n);
37     qsort(a+1,n,sizeof(a[1]),cmp);
38     for(int i=1;i<=n;i++) printf("%d%c",a[i],(i==n) ? '\n':' ');
39     return 0;
40 }

 

posted @ 2018-11-20 11:15 拦路雨偏似雪花 阅读(...) 评论(...) 编辑 收藏
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: