C++ STL之排序算法


排序算法和查找算法差不多,也涉及到迭代器區間問題,關於該問題的注意事項就不在啰嗦了

一、全部排序sort、stable_sort

sort是一種不穩定排序,使用時需要包含頭文件algorithm

默認可以傳兩個參數或三個參數。第一個參數是要排序的區間首地址,第二個參數是區間尾地址的下一地址。如果只傳入這兩個地址的話,就按照升序對指定地址區間排序。想要按照降序排列的話,需要傳入第三個函數,第三個函數可以自己寫cmp,也可以直接調用庫函數

greater<data-type>(),使用庫函數的時候要包含頭文件functional。

總結如下:

#include<algorithm>

#include<functional>

升序:sort(begin,end,less<data-type>());

降序:sort(begin,end,greater<data-type>()).

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<functional>
 4 using namespace std;
 5 int main()
 6 {
 7     int a[9]={454,45564,6,3,5,65,32,53,5};
 8     //升序
 9     sort(a,a+9,less<int>());
10     cout<<"升序排序結果"<<endl;
11     for(int i=0;i<9;i++)
12     {
13         cout<<a[i]<<endl;
14     }
15     //降序
16     sort(a,a+9,greater<int>());
17     cout<<"降序排序結果"<<endl;
18     for(int i=0;i<9;i++)
19     {
20         cout<<a[i]<<endl;
21     }
22     return 0;
23 }

如果忘記了升序或者降序后面的那個方法名稱,也可以自己寫個簡單的

bool cmp(int a,int b)
{
 return a>b;
}

sort(a,a+9,cmp);
就是降序

bool cmp(int a,int b)

{

return a<b;

}

sort(a,a+9,cmp);

就是升序

與之對應的有一個stable_sort()用法與sort一樣,是穩定排序。

二、部分排序partial_sort、partial_sort_copy

 1 #include<iostream>
 2 #include<algorithm>
 3 using namespace std;
 4 int main()
 5 {
 6     int num[10]={3,4,6,7,3,5,2,9,7,8};
 7     for(int i=0;i<10;i++)
 8     {
 9         cout<<num[i]<<" ";
10     }
11     cout<<endl;
12     //partial_sort
13     //void partial_sort(_RanIt _First, _RanIt _Mid, _RanIt _Last, _Pr _Pred)
14     //選出[_First, _Last)之間的_Mid-_First個數進行排序,放在_First到_Mid位置,剩下的在_Mid到_Last的元素不排序,pred是排序方式
15     partial_sort(num,num+3,num+10);
16     for(int i=0;i<10;i++)
17     {
18         cout<<num[i]<<" ";
19     }
20     cout<<endl;
21 
22     //partial_sort_copy
23     //_RanIt partial_sort_copy(_InIt _First1, _InIt _Last1,_RanIt _First2, _RanIt _Last2, _Pr _Pred)
24     int shuzi[10]={3,4,6,7,3,5,2,9,7,8};
25     int result1[3];
26     int result2[12];
27     partial_sort_copy(shuzi,shuzi+10,result1,result1+3);
28     for(int i=0;i<10;i++)
29     {
30         cout<<shuzi[i]<<" ";
31     }
32     cout<<endl;
33     for(int i=0;i<3;i++)
34     {
35         cout<<result1[i]<<" ";
36     }
37     cout<<endl;
38         
39     partial_sort_copy(shuzi,shuzi+10,result2,result2+12);
40     for(int i=0;i<10;i++)
41     {
42         cout<<shuzi[i]<<" ";
43     }
44     cout<<endl;
45     for(int i=0;i<12;i++)
46     {
47         cout<<result2[i]<<" ";
48     }
49     cout<<endl;
50     return 0;
51 }

 


免責聲明!

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



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