C ++ STL具有默认的排序功能,可以按递增顺序对数组或向量进行排序。通常,它使用快速排序,这种排序的最坏情况是时间复杂度为O(n ^ 2)和平均值为O(nlogn)。
排序数组:
令数组为a [n]表示数组的长度为n。要对数组进行排序,我们需要编写sort(a,a + n);
排序向量:
vector<int> a; //一个整数类型的向量
为了对向量进行升序排序,我们需要编写
sort(a.begin(),a.end());
#include <bits/stdc++.h> using namespace std; int main () { //排序数组 cout<<"............sorting an array............"<<endl; //数组定义 int arr[10] = { 34, 67, 54, 2, 4, 78, 63, 90, 12, 26 }; cout << "before sorting......." << endl; for (int i = 0; i < 10; i++) cout << arr[i] << " "; cout << endl; cout << "after sorting.........." << endl; sort (arr, arr + 10); //使用STL排序功能 for (int i = 0; i < 10; i++) cout << arr[i] << " "; cout<<endl; //排序向量 cout<<"............sorting a vector............"<<endl; vector<int> a; a.push_back(6); a.push_back(5); a.push_back(12); a.push_back(25); a.push_back(1); a.push_back(87); a.push_back(34); a.push_back(16); cout << "before sorting......." << endl; for(auto it=a.begin();it!=a.end();it++){ cout<<*it<<" "; } cout<<endl; sort(a.begin(),a.end());//使用STL排序函数 cout << "after sorting......." << endl; for(auto it=a.begin();it!=a.end();it++){ cout<<*it<<" "; } cout<<endl; return 0; }
输出结果
............sorting an array............ before sorting....... 34 67 54 2 4 78 63 90 12 26 after sorting.......... 2 4 12 26 34 54 63 67 78 90 ............sorting a vector............ before sorting....... 6 5 12 25 1 87 34 16 after sorting....... 1 5 6 12 16 25 34 87