algorithm - 对完全降序的数组进行排序时,快速排序效率低下是否正常?
问题描述
#include <iostream>
#include<stdio.h>
#include<fstream>
using namespace std;
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
int partition (int arr[], int low, int high)
{
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high- 1; j++)
{
if (arr[j] <= pivot)
{
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
int main()
{
int arr[100000];
int i;
ifstream fin;
int n = 20000;
fin.open("reverse20k.txt");
if(fin.is_open())
{
for(i=0;i<n;i++)
fin>>arr[i];
}
quickSort(arr, 0, n-1);
return 0;
}
对一个 20k 的纯降序数组进行排序大约需要 1.25 秒,而合并排序只需要 0.05 秒。对降序数组进行排序时,快速排序是不是效率极低,还是算法有问题?
解决方案
推荐阅读
- html - html : 画一条分隔线到三个
- c++ - 用于缩写超过 10 个字符的单词的代码无法正常运行
- javascript - 使用 Typescript 访问对象属性
- angularjs - 不考虑更改 angularjs 程序中的名称
- javascript - D3.js 以编程方式启用/禁用拖动
- json - uwp 覆盖 resw 文件中的本地化字符串
- javascript - 如何从 mail-chimp api 修复超级终端中出现的 MailChimp 401 错误?(使用 JavaScript)
- r - 如何使 input_shape 参数适应 R 中的表格尺寸
- swift - 无法在 wkwebview 中加载特定 url 但在 Safari 浏览器中正确加载
- reactjs - 如何检查在此测试中是否使用 Jest 调用了 signOut?