0
#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;
}

It takes this about 1.25 seconds to sort a 20k purely descending array, while it takes merge sort only 0.05. Is quick sort just extremely inefficient when sorting descending arrays, or is there just something wrong with the algorithm?

NAlexP
  • 183
  • 1
  • 16
  • 2
    Yes, it is - bubble-sort might be even faster! This is really an algorithm question, so I have re-tagged it. –  Sep 13 '18 at 23:38
  • 3
    Depends on the way you choose the pivot element. The simple version takes the leftmost (or rightmost) element. In this case, an already sorted input is the **worst case** scenario for quicksort. This can easily be solved by changing the pivot strategy, for example by using a random pivot. Also see [here](https://www.geeksforgeeks.org/when-does-the-worst-case-of-quicksort-occur/). – Zabuzard Sep 13 '18 at 23:45
  • Choosing the middle element will eliminate worst case behavior for ascending or descending data. Use `pivot = array[(low + high) / 2]` or `pivot = array[(low + (high - low) / 2]` . – rcgldr Sep 13 '18 at 23:50
  • Thanks for your input guys. @NeilButterworth yes, bubble sort is actually better for an array of 1k and 10k elements! Quick sort takes the spot at 20k elements, but after that it crashes, so you could say bubble sort is deffinitely faster! – NAlexP Sep 13 '18 at 23:53

0 Answers0