MergeSort - Out of Range !!!

Why it alway "out of range" when I excute

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
  #include<iostream>
#include<vector>

using namespace std;

void Merge(vector<int> &a, vector<int> &left ,vector<int> &right)
{
	int nl = left.size();
	int nr = right.size();
	int i= 0 , j= 0 , k = 0;
	while(i < nl && j < nr)
	{
		if ( left[i] <= right[j] )
		{
			a[k] = left[i];
			k++;
			i++;
			
		}
		if (left[i] >= right[j] )
		{
			a[k] = right[j];
			k++;
			j++;
		}
		
	}
	while(i < nl)
	{
		a[k] = left[i];
		k++;
		i++;
	}
	while(j < nr)
	{
		a[k] = right[j];
		k++;
		j++;
	}
}


void MergeSort(vector<int> &a)
{
	int n = a.size();
	if ( n < 2) 
	{
		return;
	}
	else
	{
		int mid = n/2;
		vector<int> left(mid,0);
		vector<int> right(n-mid,0);
		for (int i = 0 ; i < mid;i++)
		{
			left[i] = a[i];
		}
		for (int j = mid ; j < n;j++)
		{
			right[j-mid] = a[j];
		}
		MergeSort(left);
		MergeSort(right);
		Merge(a,left,right);
	}
} 

void Print(vector<int> &a,int n)
{
	for (int i =0;i < n;i++)
	{
		cout << a[i] << " ";
	}
}

void main()
{
	int n;
	cout <<"Enter The Number:"; cin >> n;
	vector<int> a(n,0);
	for (int i = 0;i < n;i++)
	{
		a[i] = rand() + rand() +rand();
	}
	MergeSort(a);
	Print(a,n);
	
}
closed account (SECMoG1T)
1
2
int mid = n/2;
///use mid=(n-1)/2 
Topic archived. No new replies allowed.