Merge Sort Crashing

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
/*Program to perform Merge Sort*/

#include<iostream>
using namespace std;

void mergesort(int [],int,int);
void merge(int [],int,int,int);

void mergesort(int a[],int p, int r)
{
 if(p<r)
 {
       int q=(p+r)/2;
       mergesort(a,p,q);
       mergesort(a,q+1,r);
       merge(a,p,q,r);
       
 }
}

void merge(int a[],int p, int q, int r)
{
     int n1=q-p+1;
     int n2=r-q;
     int *a1,*a2;
     int i=0,j=0,k=0;;
     a1=new int[n1];
     a2=new int[n2];
     
     for(int i=p;i<=q;i++)
     a1[j++]=a[i];
     
     j=0;
     
     for(int i=q+1;i<=r;i++)
     a2[j++]=a[i];
     
     i=0,j=0;
     
     while(i<q-p+1&&j<r-q)
     {
                          if(a1[i]<a2[j])
                          a[k++]=a1[i++];
      
                          else if(a2[j]<a1[i])
                          a[k++]=a2[j++];
     }
     
     while(i<(q-p+1))
     a[k++]=a1[i++];
     
     while(j<r-q)
     a[k++]=a2[j++];
     
}

int main()
{
    int n;
    cin>>n;
    
    int *a;
    a=new int[n];
    
    for(int i=0;i<n;i++)
    cin>>a[i];
    
    mergesort(a,0,n-1);
    
    for(int i=0;i<n;i++)
    cout<<a[i];
    
    system("pause");
    return 0;
}


My Merge Sort Program crashes whenever the number of inputs is more than 3. What is the reason?
On line 26, I believe k should be initialized to p.

You should also add a

1
2
delete [] a1;
delete [] a2;

before you return from merge.
Last edited on
Topic archived. No new replies allowed.