Ryan D. - 1 month ago 5x

C Question

I've read multiple posts on Bubble Sort, but still have difficulty verbalizing why my code works, particularly with respect to the outer loop.

`for (int i = 0; i < (n - 1); i++)`

{

for (int j = 0; j < (n - i - 1); j++)

{

if (array[j] > array[j + 1])

{

int temp = array[j];

array[j] = array[j + 1];

array[j + 1] = temp;

}

}

}

For any array of length n, at most n-1 pairwise comparisons are possible. That said, if we stop at i < n-1, we never

Answer

In this line you are accessing 1 element ahead of current position of j

```
array[j + 1];
```

In first iteration of the loop you run j from 0 to j<(n-0-1), so last index of array which you can get is j less than n, as you accessing array[j+1]. So if you declare you array as array[n], this will get the last element for your array.

Source (Stackoverflow)

Comments