Bubble Sort
I copied this code from a book and find it not to function properly. I checked it several times and still it doesn't work. Can you correct this one:
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
|
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int nums[10];
int a, b, t;
int size;
size = 10;
for (t=0; t<size; t++) nums[t] = rand();
cout << "Original array is :\n";
for (t=0; t<size; t++) cout << nums[t] << ' ';
cout << '\n';
for (a=1; a<size; a++)
for (b=size-1; b>=a;b--) {
if (nums[b-1]> nums [b]) {
t =nums[b-1];
nums[b-1] = nums[b];
nums[b] = t;
}
}
cout << "\nSorted array is:\n ";
for (t=0; t=size; t++) cout << nums[t] << ' ';
return 0;
}
|
The expected output is
Original array is: 41 18467 6334 26500 19169 15724 11478 29358 26962 24464
Sorted array is: 41 6334 11478 15724 18467 19169 24464 26500 26962 29358
I have no idea whats wrong.
line 28: should be t > size
, not t = size
Thanks. I didn't noticed that typographical error of the book.
But wait... I guess it must be t < size
. But it helps me to figure out.
Topic archived. No new replies allowed.