tags:

views:

153

answers:

3

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
+3  A: 

In your inner loop, you don't use j at all. Double check your logic. Also note that array[i+1] goes beyond the array boundary.

Igor Krivokon
+1  A: 
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.

A: 

Another thing, the inner loop goes from 0 to i if I remember well; but I think that's just an optimisation (as the tail is remains sorted in each step).

Try to run step by step your code with paper and pencil. That always works.

fortran