Strange negative number in bubble sort code

So, I found this bubble sort code somewhere on here an figured I'd give it a spin, but whenever I run it, the highest number(whatever it may be) is converted to -858993460. However many numbers I have or how high or low the number is, it's always this negative number. I was wondering if anyone had any idea why this is happening.
I noticed this happening in some other code I've done and I just sort of dismissed it.

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

#include <iostream>

using namespace std;

int main()
{
	int aray[3] = { 1, 3, 37 };

	for (int i = 0; i<3; i++)
	{
		cout << i + 1 << ") " << aray[i] << endl;
	}

	//	cin.ignore();

	/////////////////Bubble Sort/////////////////////
	for (int i = 2; i >= 0; i--)
	{
		for (int x = 0; x< 3; x++)
		{
			if (aray[x]>aray[x + 1])
			{

				int temp = aray[x + 1];

				aray[x + 1] = aray[x];

				aray[x] = temp;

			}
		}
	}
	/////////////////END:Bubble Sort///////////////

	cout << "\n---Sorted---\n\n";

	for (int i = 0; i<3; i++)
	{
		cout << i + 1 << ") " << aray[i] << endl;
	}

	cin.ignore();
	system("pause");
	return 0;

}
Your loops are switched, because when x = 2, aray[x+1] = aray[3], which doesn't have any legal value or address since the array has elements only aray[0], aray[1], aray[2].

Make it as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
int TEMP;
	for(int I = 0; I < SIZE; I++)
	{
		for(int J = 0; J < SIZE - 1; J++)
		{
			if(ARR[J] > ARR[J + 1])
			{
				TEMP = ARR[J];
				ARR[J] = ARR[J + 1];
				ARR[J + 1] = TEMP;
			}
		}
	}

Last edited on
Wow, that fixed it. I don't completely understand how, but it worked.
Thank you (:

EDIT: Woah, actually ,I take that back. I somehow managed to screw it up more. Now whatever I put in as my first number, replaces my last number. The middle number is untouched, but the first always replaces the last.

EDIT 2: Oh god, I'm an idiot. I just noticed a typo that was causing this. Sorry! Thanks for the help.

Last edited on
Topic archived. No new replies allowed.