首页 > 解决方案 > 对完全降序的数组进行排序时,快速排序效率低下是否正常?

问题描述

#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 秒。对降序数组进行排序时,快速排序是不是效率极低,还是算法有问题?

标签: algorithmsorting

解决方案


推荐阅读