Search code examples
cbubble-sort

Strange Bubble sort behaviour


Can anyone explain why this bubble sort function doesn't work and why I lose numbers in my output? I'm very new to C, so please forgive me if this is something very obvious I have missed.

#include <stdio.h>
#include <stdlib.h>

int bubble(int array[],int length) {
  int i, j;
  int temp;

  for(i = 0; i < (length); ++i) {
    for(j = 0; j < (length - 1); ++j) {
      if(array[i] > array[i+1]) {
        temp = array[i+1];
        array[i+1] = array[i];
        array[i] = temp;
      }
    }
  }
  return 0;
}

int main() {
  int array[] = {12,234,3452,5643,0};
  int i;
  int length;

  length = (sizeof(array)/sizeof(int));
  printf("Size of array = %d\n", length);
  bubble(array, length);
  for (i = 0; i < (length); ++i) {
    printf("%d\n", array[i]);
  }
  return 0;
}

Output

Size of array = 5
12
234
3452
0
0

Solution

  • for (i = 0; i < (length-1); ++i) {
      for (j = 0; j < (length-i-1); ++j) {
        if(array[j] > array[j+1]) {
          temp = array[j+1];
          array[j+1] = array[j];
          array[j] = temp;
        }
      }
    }
    

    In a bubble sort you only use the inner loop variable.