What's Wrong With My Basic Sort?

I've seen this done a few months ago, but overall, I'm trying my best to do it by myself, for the sake of my understanding. I have to sort an array of structs, so I'm just trying to get basic sorting down with a simple array. The output that I get is largely fine, except that the 12 is turned into a zero. Also, how would I get the size - would I just use the size() function?

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
#include <iostream>

using namespace std;

int main()
{

int list[10] = {6, 2, 9, 4, 1, 5, 7, 12, 3, 10};

int end = 10;
int swapNumbers = -1;

for (int count = end - 1; count > 0; count--){

for (int k = 0; k < 10; k++){

if (list[k] > list[k+1]){
swapNumbers = list[k+1];

list[k+1] = list[k];
list[k] = swapNumbers;

}}
}

//Output sorted list

for (int i = 0; i < 10; i++){
cout << list[i] << endl;
}
    return 0;
}
Last edited on
One tip:
Consider k == 9 and you access List[k+1]. What do you access? ^.^
Ahhh, I see. I suppose I had one extra iteration than needed. I changed it to k < 9, and the program is fine.

Thank you.
Last edited on
I'm still wondering how I would work this out if I had to input an array from a file. When I tried to "#include <array>" so that I could try out the size function, I got the following error message:

"#error This file requires compiler and library support for the \
ISO C++ 2011 standard. This support is currently experimental, and must be \
enabled with the -std=c++11 or -std=gnu++11 compiler options."

Also happened on online compilers that I tried.
vector class my friend ! ;)

to make it clear what happened before with List[k+1] when k == 9 => List[10] uninitialized memory space (your last List element is List[9])
Thanks again, Glandy.

Yeah, I would love to use vectors, but the particular project that I'm doing uses an array of structs, so I have to just keep on trucking until I, hopefully, get to a more flexible professor.
Topic archived. No new replies allowed.