Search code examples
carrayspointersbubble-sort

I don't understand why my code for bubble sort does not work


for (int index = 0; index < size -1; index ++) {
    for (int index2 = 0; index2 < size - index; index2 ++) {
        if (index2 != (size - index) && array[index2] > array[index2 + 1] ) {
           store = array[index2 + 1];
          array[index2 + 1] = array[index2];
          array[index2] = store;
          printf ("%d",array[index2]);
          swap ++;
          comparison ++;
        }
    }
}

So this is the code for swapping and comparing the element of arrays using bubble sort algorithm. It works for all cases but except with an array with two elements. I used C for this program. I used pointer to declare the array.

For example:

input: [2,0],
output: [0,1]

intput: [3.8],
output: [3,1]

Solution

  • it off by one error. Based on your code, the 2nd loop should be

    for (int index2 = 0; index2 < size - index -1; index2 ++){ ...