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!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <math.h> 
#include <stdlib.h>
#include <time.h>   
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<n);
	
	cout << "\nThe array is sorted using bubble sort method";
	return 0;
}
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.