qsort与sort
?sort()函數是C++中的排序函數其頭文件為:#include<algorithm>頭文件;
?qsort()是C中的排序函數,其頭文件為:#include<stdlib.h>
sort是不需要自己寫compare的,sort默認是升序排列,如果想要降序就需要寫一個compare。
#include<iostream>
#include<algorithm>
using namespace std;//sort用在c++,需要加上這個用語
int cmp(int a,int b)
{
?if(a<b)
?return 1; //升序排列,如果改為 a >b,則為降序,要注意sort()中cmp()的返值只有1和0,不像qsort中存在-1!!!!
?else
?return 0;
}
?
int main(){
?????? inti;
?inta[20];
?for(int i=0;i<5;++i)
?cin>>a[i];
sort(a,a+5,cmp);????? ???? //范圍,很明顯這里是a+5 注意,這是必要的,如果是a+4最后一個值a[4]就不會參與排序。
for(i=0;i<5;i++)??????
cout<<a[i]<<endl;
?????? system("pause");
/*system("pause")就是從程序里調用“pause”命令; 而“pause”這個系統命令的功能很簡單,就是在命令行上輸出一行類似于“Press any key to exit”的字,等待用戶按一個鍵,然后返回。*/?return 0;
}
qsort :
參數:
1 待排序數組首地址 2 數組中待排序元素數量 3 各元素的占用空間大小 4 指向函數的指針,用于確定排序的順序double類型
double in[100];
int cmp( const void *a , const void *b )
{
return *(double *)a > *(double *)b ? 1 : -1;
}
qsort(in,100,sizeof(in[0]),cmp);
一級排序:
intcomp(const?void*a,const?void*b) { return?*(int*)a-*(int*)b;升序 } *(int*)b-*(int*)a;降序二級排序:
int cmp( const void *a , const void *b )
{
struct In *c = (In *)a;
struct In *d = (In *)b;
if(c->x != d->x) return c->x -d->x;
else return d->y - c->y;
}
qsort(s,100,sizeof(s[0]),cmp);
三級排序:
int cmp(const void *a,const void *b)
{
struct node *c=(node *)a;
struct node *d=(node *)b;
if(c->no==d->no)
{
if(c->l==d->l)
{
return c->w-d->w;
}
else return c->l-d->l;
}
else return c->no-d->no;
}
qsort(a,m,sizeof(node),cmp);
總結
以上是生活随笔為你收集整理的qsort与sort的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java 计算两点坐标距离
- 下一篇: 人工智能导论(专家系统)