C++ 排序函數 sort(),qsort()的用法


C庫函數qsort,C++庫函數sort。其中qsort相對較慢,sort實現非常高效

qsort:

 

功 能: 使用 快速排序例程進行排序
頭文件:#include<qsort>
用 法: void qsort(void *base,int nelem,int width,int (*fcmp)(const void *,const void *));【qsort ( 數組名 ,元素個數,元素占用的空間(sizeof),比較函數) 】
參數: 1 待排序 數組首地址
2 數組中待排序元素數量
3 各元素的占用空間大小
4 指向函數的 指針,用於確定排序的順序

 

 

C++  qsort函數

頭文件:#include <algorithm>

默認的sort函數是按升序排。

 1 //sort(begin,end),表示一個范圍,數組a按升序排序
  //例如:
2 3 int _tmain(int argc, _TCHAR* argv[]) 4 { 5 int a[20]={2,4,1,23,5,76,0,43,24,65},i; 6 for(i=0;i<20;i++) 7 cout<<a[i]<<endl; 8 sort(a,a+20); 9 for(i=0;i<20;i++) 10 cout<<a[i]<<endl; 11 return 0; 12 }

降序:sort(begin,end,compare)

bool compare(int a,int b)
{
      return a<b;   //升序排列,如果改為return a>b,則為降序

}

為了描述方便,我先定義一個枚舉類型EnumComp用來表示升序和降序。

class compare
{
      private:
            Enumcomp comp;//枚舉類型
      public:
            compare(Enumcomp c):comp(c) {};
      bool operator () (int num1,int num2) 
         {
            switch(comp)
              {
                 case ASC:
                        return num1<num2;
                 case DESC:
                        return num1>num2;
              }
          }
};

/*接下來使用 sort(begin,end,compare(ASC)實現升序
sort(begin,end,compare(DESC)實現降序。
*/ //主函數為: int main() { int a[20]={2,4,1,23,5,76,0,43,24,65},i; for(i=0;i<20;i++) cout<<a[i]<<endl; sort(a,a+20,compare(DESC)); for(i=0;i<20;i++) cout<<a[i]<<endl; return 0; }

qsort

#include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b)
{
    int *pa = (int*)a;
    int *pb = (int*)b;
    return (*pa )- (*pb);  //從小到大排序
}
/*int cmp ( const void *p1 , const void *p2 )
{
    return *( int * )p1 - *( int * )p2 ;
}
*/
void main()
{
    int a[10] = {5, 6, 4, 3, 7, 0 ,8, 9, 2, 1};
    qsort(a, 10, sizeof(int), compare);
    for (int i = 0; i < 10; i++)
        cout << a[i] << " " << endl;
} 

建議用sort 更方便簡單些 默認是升序


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM