排序方法 | 平均时间复杂度 | 最坏的时间复杂度 | 最好的时间复杂度 | 空间复杂度 | 稳定性 | 复杂性 |
冒泡排序 | ![O(n^{2})](https://latex.csdn.net/eq?O%28n%5E%7B2%7D%29) | ![O(n^{2})](https://latex.csdn.net/eq?O%28n%5E%7B2%7D%29) | ![O(n)](https://latex.csdn.net/eq?O%28n%29) | ![O(1)](https://latex.csdn.net/eq?O%281%29) | 不稳定 | 较复杂 |
插入排序 | ![O(n^{2})](https://latex.csdn.net/eq?O%28n%5E%7B2%7D%29) | ![O(n^{2})](https://latex.csdn.net/eq?O%28n%5E%7B2%7D%29) | ![O(n)](https://latex.csdn.net/eq?O%28n%29) | ![O(1)](https://latex.csdn.net/eq?O%281%29) | 稳定 | 简单 |
快速排序 | ![O(n\log_{2}n)](https://latex.csdn.net/eq?O%28n%5Clog_%7B2%7Dn%29) | ![O(n^{2})](https://latex.csdn.net/eq?O%28n%5E%7B2%7D%29) | ![O(n\log_{2}n)](https://latex.csdn.net/eq?O%28n%5Clog_%7B2%7Dn%29) | ![O(n\log_{2}n)](https://latex.csdn.net/eq?O%28n%5Clog_%7B2%7Dn%29) | 不稳定 | 较复杂 |
归并排序 | ![O(n\log_{2}n)](https://latex.csdn.net/eq?O%28n%5Clog_%7B2%7Dn%29) | ![O(n\log_{2}n)](https://latex.csdn.net/eq?O%28n%5Clog_%7B2%7Dn%29) | ![O(n\log_{2}n)](https://latex.csdn.net/eq?O%28n%5Clog_%7B2%7Dn%29) | ![O(n)](https://latex.csdn.net/eq?O%28n%29) | 稳定 | 较复杂 |
冒泡排序
vector<int> arr({2,1,5,3,4,8,6,0});
int n = arr.size();
for(int i = 0; i < n; ++i){
for(int j = i+1; j < n; ++j){
if(arr[i] > arr[j]){
swap(arr[i], arr[j]);
}
}
}
插入排序
void insertSort(vector<int>& arr){
for(int j = 1; j < arr.size(); ++j){
int k = arr[j];
int i = j-1; //最后一个有序数的位置
while(i>=0 && arr[i]>k){ //查找插入的位置,即第一个小于等于k的位置
arr[i+1] = arr[i];
i--;
}
arr[i+1] = k;
}
}
快速排序
int divide(std::vector<int>& arr, int l, int r) {
int pos = rand() % (r - l + 1) + l; //[l, r]区间内随机选一个位置
std::swap(arr[pos], arr[l]);
int cur = arr[l]; //标准数
while (l < r) { //出口条件为l == r
while (l < r && arr[r] >= cur)
--r;
arr[l] = arr[r];
while (l < r && arr[l] <= cur)
++l;
arr[r] = arr[l];
}
arr[l] = cur;
return l;
}
void quick_sort(std::vector<int>& arr, int l, int r) {
if (l < r) {
int mid = divide(arr, l, r);
quick_sort(arr, l, mid-1);
quick_sort(arr, mid+1, r);
}
}
int main()
{
std::vector<int> arr({5,3,1,4,8});
srand((unsigned)time(NULL));
for (int i : arr) {
std::cout << i << " ";
}
quick_sort(arr,0,arr.size()-1);
std::cout << "--------------" << std::endl;
for (int i : arr) {
std::cout << i << " ";
}
return 0;
}
归并排序
void merge_sort(std::vector<int>& arr, int l, int r, std::vector<int>& temp) {
if (l < r) {
int mid = l + ((r - l) >> 1);
merge_sort(arr, l, mid, temp);
merge_sort(arr, mid+1, r, temp);
int p1 = l;
int p2 = mid + 1;
int p = 0;
while (p1 <= mid && p2 <= r) {
if (arr[p1] < arr[p2]) {
temp[p++] = arr[p1++];
}
else {
temp[p++] = arr[p2++];
}
}
while (p1 <= mid) {
temp[p++] = arr[p1++];
}
while (p2 <= r) {
temp[p++] = arr[p2++];
}
p = 0;
for (int i = l; i <= r; ++i) {
arr[i] = temp[p++];
}
}
}
int main()
{
std::vector<int> arr({5,3,1,4,8});
srand((unsigned)time(NULL));
for (int i : arr) {
std::cout << i << " ";
}
std::vector<int> temp(arr.size());
merge_sort(arr, 0, arr.size()-1, temp);
std::cout << "--------------" << std::endl;
for (int i : arr) {
std::cout << i << " ";
}
return 0;
}