Exception Thrown

Im trying to sort an array without using sort built-in function and i dont know why im getting this error ( using visual studio 2017)

Exception thrown at 0x00902597 in learning2.exe: 0xC0000005: Access violation writing location 0x007F0008.

Last edited on
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
#include <iostream> 
#include <algorithm> 

using namespace std;

int main()
{
	int n=4, temp=0;
	int a[4] = { 3,1,2,4 };

	for (int i = 0; i < n; i++)
		cin >> a[i];

	for (int i=0; i <n;i++)
		for (int j = i+1; i < n; j++)
		{
			if (a[i] > a[j])
			{
				temp = a[i];
				a[j] = temp;
				a[i] = a[j];
			}
		}

	for (int i = 0; i < n; i++)
		cout << a[i] << " ";
}
Last edited on
I don't see the unresolved external.

You don't need <algorithm> in your code.

Line 15 should probably be for (int j = i + 1; j < n; j++)

Your swap is wrong. Lines 20 and 21 should probably be
1
2
a[i] = a[j];
a[j] = temp;



Edit: You can compile the code online by clicking the little gear. If you make the changes I suggest, it will compile and run in another browser tab.

Also, you don't need to initialize your array in line 9 if you are going to populate it again in lines 11 and 12.
Last edited on
Topic archived. No new replies allowed.