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 }
還寫了一個純排序的代碼,非結構體的。手寫快排,或者用系統自帶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 }