### Bubble sorting of an random array

Was trying to make sorting of array using bubble sort method. Everything works fine except one thing, biggest number doesn't appear in sorted array, but instead of it there is number before it repeated twice. Can't get why is that happening. And unfortunately couldn't find answer in other posts.
Explanation is appreciated. Thank you!

 ``1234567891011121314151617181920212223242526272829303132333435363738394041`` ``````#include #include #include #include using namespace std; int main() { int i, j,n=20, temp; int a [n]; srand (time(NULL)); cout << "This our initial random array\n"; for (i = 0; i < 20; i++) { a[i] = rand() % 100 + 1; cout << a[i] << " "; } cout << "\n"; i = 0; j = 0; do { j=n-1; do { if (a[j-1]>a[j]) { temp = a[j-1]; a[j-1] = a[j]; a[j] = temp; } else j=j-1; } while (j>i); i=i+1; cout << a[j] << " "; } while (i
Last edited on
try j>=i on 34.
not 100% sure, but easy to check.
if not try i<=n on 37. I think its one of those but trying to read this quickly & getting lost in the loops.
Last edited on
Unfortunately, the way that you have phrased the logic (which is very unusual for bubble-sort) line 33 will always be carried out. Starting with j=n-1 you will always drop at least to n-2 and never print out the last value itself if you try to do so during this variant of the sorting operation.

Also, i corresponds to the lowest value of j-1, so the last value of i need only be n-2, whereas line 37 implies it is n-1.

Your array IS actually sorted, as you would find if you printed everything after sorting. It's just that trying to print out as you go along is not matching your looping conditions.

If you want to sort with these loops, then just print out the whole array after sorting, not during it.

Line 32 (just "else") is also redundant. You always want this to happen.

Last edited on
Thank you! Everything works just fine now.
Topic archived. No new replies allowed.