关于C语言中sort
函数的使用方法,根据不同的编程语言特性和标准库实现,主要分为以下两种情况:
一、C语言中的qsort
函数
-
函数原型
int qsort(void *base, size_t num, size_t size, int (*compar)(const void *, const void *));
-
base
:指向数组首元素的指针; -
num
:要排序的元素个数; -
size
:每个元素的大小(以字节为单位); -
compar
:比较函数指针,用于定义排序规则。
-
-
默认排序规则
若未提供比较函数,
qsort
按 升序 排序(即从小到大)。 -
自定义比较函数
-
升序 :
return a - b;
-
降序 :
return b - a;
示例:
#include <stdio.h> #include <stdlib.h> int compare(const void *a, const void *b) { int int_a = *(int *)a; int int_b = *(int *)b; return int_a - int_b; } int main() { int arr[] = {5, 2, 8, 1, 9}; size_t n = sizeof(arr)/sizeof(arr); qsort(arr, n, sizeof(int), compare); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; }
-
二、C++标准库中的sort
函数
-
函数模板
template <class InputIt, class Compare = std::less<InputIt>> void sort(InputIt first, InputIt last, Compare comp = Compare());
-
first
和last
:迭代器,表示要排序的范围(如数组或容器); -
comp
:可选的比较函数,用于定义排序规则(默认为std::less
,即升序)。
-
-
使用示例
-
升序排序 :
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> numbers = {3, 1, 5, 2, 4}; sort(numbers.begin(), numbers.end()); for (int num : numbers) { std::cout << num << " "; } return 0; }
-
降序排序 :
std::sort(numbers.begin(), numbers.end(), std::greater<int>());
-
自定义类型排序 :
struct Product { std::string name; float price; }; bool compareByPrice(const Product &a, const Product &b) { return a.price < b.price; } int main() { std::vector<Product> products = {{"Apple", 0.5}, {"Banana", 0.3}}; sort(products.begin(), products.end(), compareByPrice); for (const auto &p : products) { std::cout << p.name << " $" << p.price << std::endl; } return 0; }
-
-
时间复杂度
C++的
sort
通常基于快速排序,平均时间复杂度为 O(n log n) ,最坏情况下为 O(n²) (当输入数据已排序时)。
总结
-
C语言 使用
qsort
函数,需手动定义比较函数,适用于静态数组排序; -
C++标准库 提供
sort
函数模板,支持范围排序和自定义比较函数,适用于动态容器(如vector
)和自定义数据类型。