# bubble sort directional problems

• 01-21-2010
budala
bubble sort directional problems
I want to sort an array using bubble sort. I know it's the slowest but i have only 5-10 elements so it's fast enough. My algorithm for bubble sort works cause if I code this

Code:

```void Bubble(int array[], int length, int direction) {         int i, j;                 for (i=0; i<(length-1); i++)         {                 for (j=0; j<(length-i-1); j++)                 {                         if (array[j] > array[j+1])                                 Swap(&array[j], &array[j+1]);                 }         } }```
for the array
Code:

`884, 275, 470, 890, 860`
i get as expected
Code:

`275, 470, 860, 884, 890`

I also want the user to determine in which direction the array is sorted, up or down, but here is the problem because I get a stupid response.

Code:

```void Bubble(int array[], int length, int direction) {         int i, j;                 for (i=0; i<(length-1); i++)         {                 for (j=0; j<(length-i-1); j++)                 {                         if (direction == 1)                                 if (array[j] > array[j+1])                                   Swap(&array[j], &array[j+1]);                         else                                 if (array[j] < array[j+1])                                         Swap(&array[j], &array[j+1]);                 }         } }```
but now i get this
Code:

`860, 890, 470, 275, 884`
and it's ming boggling why!!
• 01-21-2010
ForzaItalia2006
Quote:

Originally Posted by budala

Code:

```                        if (direction == 1)                                 if (array[j] > array[j+1])                                   Swap(&array[j], &array[j+1]);                         else                                 if (array[j] < array[j+1])                                         Swap(&array[j], &array[j+1]);```

Hey,

the C compiler always binds the "else" to the inner-most if, so that your else is not bound to the "if (direction == 1)". Your indention however easily leads to the assumption that your code must be correct. Instead rewrite your code as follows:

Code:

```                        if (direction == 1)                         {                                 if (array[j] > array[j+1])                                   Swap(&array[j], &array[j+1]);                         }                         else                         {                                 if (array[j] < array[j+1])                                         Swap(&array[j], &array[j+1]);                         } }```
- Andi -