简体   繁体   中英

Quicksort function keeps returning “exited, segmentation fault”

I am trying to get this quicksort function to work but it runs into the error "exited, segmentation fault". Can I please get some help? The function stopped working when I combined the while loops using the && Operator.

#include <stdio.h>

void swap(int a[], int b, int c){
  int temp=a[b];
  a[b]=a[c];
  a[c]=temp;

}

void quicksort_fixed(int *number,int first,int last){
      int pivot=last;
      int smaller_index=first;
      int loop_variable=last;

   if(first<last){

      while((number[smaller_index] <= number[pivot])&&(smaller_index < loop_variable)){
        //printf("smaller index (%d) is less than pivot",smaller_index);
        smaller_index++;
        }
      while((number[loop_variable] > number[pivot])&&(smaller_index < loop_variable)){
        //printf("loop variable (%d) is greater than pivot",loop_variable);
        loop_variable--;
        }
        if(smaller_index < loop_variable){
          swap(number,smaller_index,loop_variable);
        }
    }

      swap(number,last,loop_variable);
      quicksort_fixed(number,first,loop_variable-1);
      quicksort_fixed(number,loop_variable+1,last);

}

void test_quicksort_fixed(){
  printf("\nUnsorted List 1: "); // First Test with small consecutive numbers
  int  a[6] = {5,2,3,1,4,6};
  for (int i=0; i < 6; i++){
    printf("%d, ", a[i]);
  }
  printf("\nSorted List 1: ");
  quicksort_fixed(a,0,5);
  for (int i=0; i < 6; i++){
    printf("%d, ", a[i]);
  }

You are missing the base case on your quicksort function. When the recursive calls are outside the if statement, they will keep spawning more recursive calls. Eventually, this will require too many stack frames (you run into a StackOverflow.) and the program will try and access memory it doesn't have (hence the segmentation fault).

Here is a correct implementation:

void quicksort_fixed(int *number, int first, int last) {
  int pivot = first;

  if (first < last) {

    for (int j = first; j < last; j++) {
      if (number[j] < number[last]) {
        swap(number, pivot, j);
        pivot++;
      }
    }
    swap(number, last, pivot);

    quicksort_fixed(number, first, pivot - 1);
    quicksort_fixed(number, pivot + 1, last);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM