Bubble Sorting array, sorted Array contains different values

Hey guys, I'm playing around with Bubble Sort in order to sort a small randomly generated array. This problem is, the sorted array and the original array contain different values...

I'm only generating the elements of the array once, so I don't really know what's going on.

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
42
43
44
45
46
47
48
49
/*  Bubble Sort demonstration
 */
 
#include <iostream>
#include <cstdlib>
 
using namespace std;
 
int main() {
 
    int a, b, t;    // initialise loop counters
    int list[10];   // initialise integer array
    int size = 10;  // size of the array to be sorted
 
    srand(clock()); // generate rand() seed

    for(t = 0; t < size; t++) {   // load array with random numbers
        list[t] = rand() % 10000;
    }
 
    // print the original array
    cout << "\n   **** Orginal Array ****\n";
    cout << "  - ";
    for(t = 0; t < size; t++) {
        cout << list[t] << " - ";
    }
    cout << "\n\n";
 
    // this is Bubble Sort
    for(a = 0; a < size; a++) {
        for(b = size-1; b >= a; b--) {
            if(list[b-1] > list[b]) {   // if out of order
                // exchange elements
                t = list[b-1];
                list[b-1] = list[b];
                list[b] = t;
            }
        }
    }
 
    // print the sorted array
    cout << "   **** Sorted Array *****\n";
    cout << "  - ";
    for(t = 0; t < size; t++){
        cout << list[t] << " - ";
    }
    cout << "\n";
    return 0;
}
Last edited on
Works for me (with a couple minor changes). http://coliru.stacked-crooked.com/a/1258c96d8e1e05a8
Last edited on
@naraku9333

Thanks buddy, I'll add those changes.
Someone had suggested before for me to use time(0) instead of clock(), so I'll give that a go..

** edit **

That seems to have fixed it, I don't know why... maybe it's the use of time(0).
Anyway, thanks again :-)
Last edited on
Topic archived. No new replies allowed.