Warm tip: This article is reproduced from stackoverflow.com, please click
c quicksort segmentation-fault

Why is this quicksort algorithm implementation code getting Segmentation fault error?

发布于 2020-03-27 10:22:51

I am working on implementing the quicksort algorithm on c language.When i compile,it says segmentation fault and i cannot find the cause of it.I looked up GeeksForGeeks about quicksort and it is my attempt at it.

    #include<stdio.h>

    void swap(int *a,int *b){
        int temp=*a;
        *a=*b;
        *b=temp;
    }

    int partition(int arr[],int first,int last){
        int pivot=arr[last];
        int i=first-1;
        for(int j=first;j<=last-1;j++){
            if(arr[j]<=pivot){
            i++;
            swap(&arr[i],&arr[j]);
        }
     }
     swap(&arr[i+1],&arr[last]);
     return (i+1);
   }

   void quickSort(int arr[],int first,int last){
       int pivot=partition(arr,first,last);
       quickSort(arr,first,pivot-1);
       quickSort(arr,pivot+1,last);
   }



   int main() {
      int arr[]={1,8,3,9,4,5,7};
      int size=sizeof(arr)/sizeof(arr[0]);
      quickSort(arr,0,size-1);
      for(int i=0;i<size;i++){
          printf("%d ", arr[i]);
      }
   }

I was expecting to see 1 3 4 5 7 8 9 but i got Segmentation fault.

Questioner
Ayano
Viewed
124
S.S. Anne 2019-07-03 22:50

Inside quickSort, you need to check that first is less than last:

   void quickSort(int arr[],int first,int last)
   {
       if(first < last)
       {
           int pivot=partition(arr,first,last);
           quickSort(arr,first,pivot-1);
           quickSort(arr,pivot+1,last);
       }
   }

You might also give attribution to GeeksForGeeks, as this code looks extremely similar to theirs.