Search code examples
c++recursionquicksortcoredump

quickSort segmentation fault (core dumped)


I know there have been multiple answers towards my problem and I understand why it is but my main problem is how to overcome this error. I know I am trying to access memory that I do not have access to but I just don't see how I am doing this.

#include <iostream>
#include <string> 
#include <stdlib.h>
using namespace std;

int arr[] = {4,5,2,1,3};
int lengd = sizeof(arr)/sizeof(arr[0]);

void swapNumber(int arr[], int i, int j){
     int tmp = arr[i];
     arr[i] = arr[j];
     arr[j] = tmp;
}

void partition(int arr[], int i, int j){
     int pivot = arr[j];
     while (i <= j) {
          while (arr[i] < pivot){
               i++;
          }
          while (arr[j] > pivot){
               j--;
          }
          if (i <= j) {
               swapNumber(arr, i, j);
               i++;
               j--;
          }
     }
}

void quickSort(int arr[], int left, int right) {
      int i = left;
      int j = right;

      partition(arr,left,right);


      if (left < j){
          quickSort(arr,left, j);
      }
      if (i < right){
          quickSort(arr, i, right);
      }
}

int main(){
    quickSort(arr,0, lengd-1);

    for(int i = 0; i < 5; i++){
        cout << arr[i] << endl;
     }
}

The error occurs when I run the quickSort function inside of the quickSort function. I don't have a clue what to do.


Solution

  • As your numbers won't be modified in your partition function, you should change its signature to receive reference:

    void partition(int arr[], int& i, int& j)
    

    and everything will work fine.

    It's easy to spot such flaws using a debugger or well-placed console messages!