Search code examples
csegmentation-faultbubble-sort

C seg fault in bubble sort variation


My code is as follows:

  void bubbleSort(char *array, int size){
   int sorted = 0;
   int x;
   while(!sorted){
      int start = 0; 
      int stop = size; 

    sorted = 1;
    for(x = start; x < stop; x++){
        if(array[x] > array[x+1]){
            swap(array[x], array[x+1]);
            sorted = 0;
        }
    }
    if(sorted){
        break;
    }
    sorted = 1;
    for(x = stop; x > start; x--){
        if(array[x-1] > array[x]){
            swap(array[x], array[x-1]);
            sorted = 0;
        }
    }
 }
 }

and based off the algorithm:

 sorted = false
 while (!sorted){

  start = start element of sublist.
  stop = stop element of sublist.

  sorted = true
  for (x = start; x < stop  ; x++){
     if Numbers[x] > Numbers[x+1]{
        swap(Numbers[x], Numbers[x+1]);
        sorted = false;
     }
  }

  if (sorted) break;

  sorted = true
  for (x = stop; x > start ; x--){
     if Numbers[x-1] > Numbers[x]{
        swap(Numbers[x], Numbers[x-1]);
        sorted = false;
     }
  }
}

This is a variation of classic bubblesort in that the full list is processed each time and the sort is performed in both directions. Any help would be much appreciated.


Solution

  • Using sizeof to get the size of array is tricky in C, that it only gives you the right answer when applied to the original array. For example,

    int array[10];
    int len = sizeof(array); // => 10 * sizeof(int)
    

    However when applied to a pointer, as you did in your bubbleSort function, it only gives the size of an int pointer. You'll have to pass the size of the array along with the pointer to your function.