1. 程式人生 > >c語言中使用自帶的qsort(結構體排序)

c語言中使用自帶的qsort(結構體排序)

c中沒有自帶的sort函式emm

不過有自帶的qsort函式

(其實用法都差不多(只是我經常以為c中有sort

標頭檔案要用

 1 #include <stdlib.h> 

一定要重新把指標指向的值賦值給一個node型別,不然比較不了

 1 struct node{
 2     int d,id,tmp;
 3 }a[N];
 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[N]; 10 int b[N],q[N],ans[N]; 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 }