Why won't this code work to order my array from least to greatest?

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
 
#include <iostream>
#include <cstdlib> 
using namespace std;

int main ()
{
    int prv_num;
    int people [] = {10,1,30,50,20,100,90,15,40,25};
    for (int index = 0; index < 10; index++)
    {
        if (people[index] > people[index + 1])
        {
            prv_num = people[index + 1];
            people[index + 1] = people[index];
            people[index] = prv_num;
        }
    }
    
    for (int index = 0; index < 10; index++)
    {
        cout<<people[index]<<", ";
    }
    
}

1, 10, 30, 20, 50, 90, 15, 40, 25, 0, 


It is suppose to output:
1,10,30,20,50,90,15,40,25,100


Can someone explain to me why this doesn't work. It replaces my highest number with a zero. WHY??? Can it be my compilers fault. I'm using Xcode on mac.
Last edited on
You need to iterate through the array several times (you only do it once). See link for more information:

http://www.cplusplus.com/faq/sequences/sequencing/sort-algorithms/bubble-sort/

It replaces my highest number with a zero. WHY???

This likely happens because of this:

if (people[index] > people[index + 1])
When index is 9, you compare the value at that index (which is the last index) with an element past the end of the array.
Topic archived. No new replies allowed.