C++排序算法

本文详细介绍C++中数组和vector的排序方法,包括基本排序、递减排序及自定义排序规则。通过实例演示如何使用std::sort进行高效排序,并解析了STL排序算法IntroSort的内部实现机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数组排序

#include <algorithm>
int v[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0};
std::sort(v, v + sizeof(v) / sizeof(v[0]));

或者

#include <algorithm>
int main(){
  int v[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0};
  std::sort(std::begin(v), std::end(v));
}

vector排序

int main() 
{ 
    vector<int> v{ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; 
  
    sort(v.begin(), v.end()); 
  
    cout << "Sorted \n"; 
    for (auto x : v) 
        cout << x << " "; 
  
    return 0; 
} 

递减排序

#include <algorithm>
int main(){
    vector<int> v{1, 5, 8, 9, 6, 7, 3, 4, 2, 0};
    sort(v.begin(), v.end(),greater<int>());
}

自定义排序规则

using namespace std; 
  
// An interval has start time and end time 
struct Interval { 
    int start, end; 
}; 
  
// Compares two intervals according to staring times. 
bool compareInterval(Interval i1, Interval i2) 
{ 
    return (i1.start < i2.start); 
} 
  
int main() 
{ 
    vector<Interval> v { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } }; 
  
    // sort the intervals in increasing order of 
    // start time 
    sort(v.begin(), v.end(), compareInterval); 
  
    cout << "Intervals sorted by start time : \n"; 
    for (auto x : v) 
        cout << "[" << x.start << ", " << x.end << "] "; 
  
    return 0; 
} 

sort的内部实现

C标准没有谈及它的qsort的复杂性。新的C ++ 11标准要求在最坏的情况下排序的复杂性为O(Nlog(N))。早期版本的C ++(如C ++ 03)允许O(N ^ 2)的最坏情况。只需要平均复杂度为O(N log N)。
STL的排序是IntroSort。IntroSort本质上是一个QuickSort,引入的差异改变了最坏的情况复杂性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值