This is a very obscure version of bubble sort! I think you are actually outputting the second largest three times.
Your i loop runs too many times and you write out at the end of each loop irrespective of whether that loop was necessary. With your current logic you have no conceivable way of outputting bubbleArray[n-1], the last entry, since you started at n-1 and subtracted 1 at least once.
The outer loop in bubblesort should run (a maximum of) n-1 times, but you need to output n numbers. So don't do both together: sort first and then output the array. (In fact I would probably sort in a separate function).
Change your logic to do all the loop tests at the start of the loop or (better) change to entirely for-loops: you know exactly how many times each has to run.
Line 10 is illegal in standard c++ (at the moment).
Line 33 is redundant and makes you do the check twice if you swap anything.
Like many sorting algorithms, it's quite nice by recursion. Actually, in this instance I think it would make the limits in the non-recursive version more obvious.
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
|
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
using namespace std;
void bubbleSort( int A[], int n )
{
if ( n > 1 )
{
for ( int j = 0; j < n - 1; j++ ) if ( A[j] > A[j+1] ) swap( A[j], A[j+1] );
bubbleSort( A, n - 1 );
}
}
int main()
{
const int N = 10;
int A[N];
srand( time( 0 ) );
for ( int &e : A ) e = 1 + rand() % 100;
cout << "Original: ";
for ( int e : A ) cout << e << ' ';
bubbleSort( A, N );
cout << "\nSorted: ";
for ( int e : A ) cout << e << ' ';
}
|
Original: 26 26 83 22 47 98 69 15 68 90
Sorted: 15 22 26 26 47 68 69 83 90 98 |