bubble sort array

i was wondering if someone could look at this.
im trying to get these numbers {1,7,4,0,9,4,8,8,2,4} into this order
{9,8,8,7,4,4,4,2,1,0}.
but once it goes down to 0 it push it off or something and outputs
7, 4, 1, 9, 4, 8, 8, 2, 4, 0
7, 4, 1, 9, 4, 8, 8, 2, 4, 2665608

so if you could help it would really me alot thanks!

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

/* 
 * File:   main.cpp
 * Author: Matt
 *
 * Created on July 26, 2012, 12:48 PM
 */

#include <iostream>
#include <cstdlib>

using namespace std;

int main(int argc, char** argv) {
    
    int Hold;//Holds value to swap
    int end = 10;
    int length = 10;
    
    
    int sortArray[] = {1, 7, 4, 0, 9, 4, 8, 8, 2, 4};//Sort greatest to lowest
    
    for(int count = length + 1; count > 0; count-- )
    {
        for (int i = 0; i < end; i++)//Goes through sortArray
        {
            if (sortArray[i] < sortArray[i +1])//i = 1 less than i = 7
            {
                Hold = sortArray[i];//Hold = 1          i = 1
                sortArray[i] = sortArray[i +1];//7 = 7
                sortArray[i + 1] = Hold;//7 = 1
            }
        for(int i = 0; i < 10 ; i++)
            {
                cout<< sortArray[i]<<", ";
            }
            cout<<endl;
        }
        end--;
    }
    
//    for(int i = 0; i < 10 ; i++)
//    {
//        cout<< sortArray[i]<<" ";
//    }
//    cout<<endl;
    return 0;
}
This code is already invalid because you are ttrying to access an alement outside the array

1
2
3
        for (int i = 0; i < end; i++)//Goes through sortArray
        {
            if (sortArray[i] < sortArray[i +1])//i = 1 less than i = 7 


That is when i == end - 1 you are ttrying to access the element sortArray[i +1] index of which is equal to end ( == 10 ).
Last edited on
thanks i just changed
 
int end = 10;


to

 
int end = 9;


and it ran all the way though and got 9,8,8,7,4,4,4,2,1,0.
Topic archived. No new replies allowed.