Question

I am trying to get quicksort working for an array of integers but for some reason it is not sorting correctly.

#include <conio.h>
#include <iostream>

#include <stdlib.h>



using namespace std;
int partition(int * arr, int left, int right, int index);
int quicksort(int * arr, int left, int right);

int main(void){
    int arr[] = { 5,0,7,2,9,4,1,3,6,8 };


    quicksort(arr, 0, 9);
    for (int i = 0; i < 10; i++){
        cout << arr[i] << std::endl;
    }

}
int quicksort(int * arr, int left, int right){
    int pivot = 0;

    if (left < right){
        pivot = partition(arr, left, right, pivot);
            for (int i = left; i <= right; i++){
        cout << arr[i] << " ";
    }
    cout << std::endl;
        quicksort(arr, left, pivot - 1);
        quicksort(arr, pivot + 1, right);
    }
    return 0;
}

int partition(int *arr, int left, int right, int index){
    int pivotValue = arr[index];
    int storedIndex = left;
    int tmp;

    tmp = arr[index];
    arr[index] = arr[right];
    arr[right] = tmp;



    for (int i = left; i < right; i++){
        if (arr[i]<= pivotValue){
            tmp = arr[i];
            arr[i] = arr[storedIndex];
            arr[storedIndex] = tmp;


            storedIndex++;
        }
    }

    tmp = arr[storedIndex];
    arr[storedIndex] = arr[right];
    arr[right] = tmp;

    return storedIndex;





}

I followed the algorithm on WikiPedia Quicksort but it still doesn't work. What am I doing wrong??

0 2 4 1 3 5 8 9 6 7
0 2 4 1 3
0 4 1 2
1 3 4
2 9 6 8
6 7 9
8 0 1 3 4 5 2 6 7 9 
Press any key to continue . . .
Was it helpful?

Solution

Your pivot element is always the first element of the array. Either call quicksort with subarrays or call it with initial pivot index. The code below does the latter.

#include <iostream>
#include <stdlib.h>

using namespace std;
int partition(int *arr, int left, int right, int index);
int quicksort(int *arr, int left, int right, int pivot);

int main(void) {
  int arr[] = {5, 0, 7, 2, 9, 4, 1, 3, 6, 8};

  quicksort(arr, 0, 9, 0);
  for (int i = 0; i < 10; i++) {
    cout << arr[i] << std::endl;
  }
}
int quicksort(int *arr, int left, int right, int pivot) {
  //int pivot = 0;

  if (left < right) {
    pivot = partition(arr, left, right, pivot);

    quicksort(arr, left, pivot - 1, left);
    quicksort(arr, pivot + 1, right, pivot + 1);

  }
  return 0;
}

int partition(int *arr, int left, int right, int index) {
  int pivotValue = arr[index];
  int storedIndex = left;
  int tmp;

  tmp = arr[index];
  arr[index] = arr[right];
  arr[right] = tmp;

  for (int i = left; i < right; i++) {
    if (arr[i] <= pivotValue) {
      tmp = arr[i];
      arr[i] = arr[storedIndex];
      arr[storedIndex] = tmp;

      storedIndex++;
    }
  }

  tmp = arr[storedIndex];
  arr[storedIndex] = arr[right];
  arr[right] = tmp;

  return storedIndex;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top