problem with bubble sort

I'm trying to get my bubble sort to work on this array, but for some reason it keeps crashing and I have no clue what the problem might be.

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
#include<iostream>
using namespace std;
void sort(int arr[]);//function to sort array

int main()
{
	int arr[3];//array used to store the 4 values
	//gets and stores array values
	cout << "Enter 4 numbers \nThe first number :";
	cin >> arr[0];
	cout << endl << "The second number : ";
	cin >> arr[1];
	cout << endl << "The third number : ";
	cin >> arr[2];
	cout << endl << "The forth number : ";
	cin >> arr[3];
	sort(arr);
	cout << "Max equals : " << arr[3];

	

}
void sort(int arr[])
{
	int num = 3;
	for (int i = 0; i < num; ++i)//for loop used to sort the array into numeric order
	{
		for (int j = 0; j < num - i - 1; ++j)
			if (arr[j] > arr[j + 1])
			{
				int temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
	}

}
i think the mistake is in line on 7 you created 3, once you enter the 4 number it crashes might want to change that number
Last edited on
Your array has FOUR numbers in:
arr[0]
arr[1]
arr[2]
arr[3]
Fix lines 7 and 25.
oh man thanks guys I just started learning about arrays and this was driving me nuts it works now. I got confused thinking I needed to use 3 because arrays use 0 instead of 1 as the starting array number.
Topic archived. No new replies allowed.