c++排序的几种方法

在 C++ 中,有多种实现排序的方法,下面为你详细介绍几种常见的排序方式:

1. 使用标准库的 std::sort

std::sort 是 C++ 标准库 <algorithm> 头文件中提供的一个通用排序函数,它基于快速排序(在某些实现中会结合其他排序算法以提高效率),时间复杂度平均为O(nlogn)。

#include <iostream> 
#include <algorithm> 
#include <vector> 
 
int main() { 
    std::vector<int> numbers = {5, 2, 8, 1, 9}; 
 
    // 使用 std::sort 进行排序 
    std::sort(numbers.begin(),  numbers.end());  
 
    // 输出排序后的结果 
    for (int num : numbers) { 
        std::cout << num << " "; 
    } 
    std::cout << std::endl; 
 
    return 0; 
} 

代码解释: 

  • 首先包含必要的头文件 <iostream> 用于输入输出,<algorithm> 提供 std::sort 函数,<vector> 用于创建动态数组。
  • 创建一个包含整数的 std::vector
  • 调用 std::sort 函数,传入容器的起始迭代器和结束迭代器,对容器内的元素进行排序。
  • 最后使用范围 for 循环输出排序后的元素。

2. 使用 std::stable_sort

std::stable_sort 同样位于 <algorithm> 头文件中,它能够保持相等元素的相对顺序,时间复杂度为 O(nlogn)。

示例代码

#include <iostream> 
#include <algorithm> 
#include <vector> 
 
struct Person { 
    std::string name; 
    int age; 
}; 
 
bool compareByAge(const Person& a, const Person& b) { 
    return a.age  < b.age;  
} 
 
int main() { 
    std::vector<Person> people = { 
        {"Alice", 25}, 
        {"Bob", 20}, 
        {"Charlie", 25} 
    }; 
 
    // 使用 std::stable_sort 进行排序 
    std::stable_sort(people.begin(),  people.end(),  compareByAge); 
 
    // 输出排序后的结果 
    for (const auto& person : people) { 
        std::cout << person.name  << " (" << person.age  << ")" << std::endl; 
    } 
 
    return 0; 
} 

 

代码解释

  • 定义一个 Person 结构体,包含姓名和年龄两个成员。
  • 编写一个比较函数 compareByAge,用于指定排序规则,这里按照年龄从小到大排序。
  • 创建一个存储 Person 对象的 std::vector
  • 调用 std::stable_sort 函数,传入容器的起始迭代器、结束迭代器和自定义的比较函数,对容器内的元素进行稳定排序。
  • 最后使用范围 for 循环输出排序后的元素。

3. 手写排序算法(以冒泡排序为例)

冒泡排序是一种简单的排序算法,其原理是多次比较相邻的元素并交换位置,将较大的元素逐步“冒泡”到数组的末尾。时间复杂度为 �(�2)O(n2)。

示例代码

#include <iostream> 
#include <vector> 
 
void bubbleSort(std::vector<int>& arr) { 
    int n = arr.size();  
    for (int i = 0; i < n - 1; ++i) { 
        for (int j = 0; j < n - i - 1; ++j) { 
            if (arr[j] > arr[j + 1]) { 
                // 交换 arr[j] 和 arr[j+1] 
                int temp = arr[j]; 
                arr[j] = arr[j + 1]; 
                arr[j + 1] = temp; 
            } 
        } 
    } 
} 
 
int main() { 
    std::vector<int> numbers = {5, 2, 8, 1, 9}; 
 
    // 使用冒泡排序 
    bubbleSort(numbers); 
 
    // 输出排序后的结果 
    for (int num : numbers) { 
        std::cout << num << " "; 
    } 
    std::cout << std::endl; 
 
    return 0; 
} 

代码解释

  • 定义一个 bubbleSort 函数,接收一个 std::vector<int> 类型的引用作为参数。
  • 使用两层嵌套的 for 循环进行元素比较和交换,外层循环控制排序的轮数,内层循环控制每一轮的比较次数。
  • 在主函数中创建一个包含整数的 std::vector,调用 bubbleSort 函数对其进行排序,最后输出排序后的结果。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值