Runtime error with sorting code

I'm doing a bubble sort code but I'm getting a debug error "Run-time check failure 2 - s". I did the code at first to sort in descending order and it worked fine but now in ascending order it's not working. Everything sorts but the first number does not move and is replaced with -858993460. What's causing this?

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>

void bsort(int saidi[5]) {
	int temp;
	for (int i=0;i<5;i++){
		for (int i = 0; i < 5; i++) {
			if (saidi[i] > saidi[i + 1]) {
				temp = saidi[i];
				saidi[i] = saidi[i + 1];
				saidi[i + 1] = temp;
			}
		}
	}
	std::cout << "The sorted SAIDI values are:";
	for (int i = 0; i < 5; i++) {
		std::cout << " " << saidi[i];
	}
}

int main() {
	int values[] = { 123, 34, 86, 53, 70 };
	bsort(values);

	return 0;
}
the program seemingly produces desired output here:http://coliru.stacked-crooked.com/a/e2ce52199b58b52c
but on my laptop (windows 10, gcc 5.9.2) it produces:The sorted SAIDI values are: 25 34 53 70 86
the reason for the spurious output in the latter case is this bit of the program:
1
2
for (int i=0;i<5;i++){
		for (int i = 0; i < 5; ++i)

you need to have a separate variable for the inner loop that runs from i+1 to < 5:
1
2
for (int i=0;i<5;i++){
		for (int j = i+1; j < 5; ++j) {//pre-increment is more efficient than post-increment 

Last edited on
Thanks a lot that worked. Isn't it strange that it worked for the descending order though?
Topic archived. No new replies allowed.