What's wrong with my merge sort code?

It's working but it's doing something funny

if my input is: 1 7 4 0 9 4 8 8 2 4

my output is: 2 8 8 8 9 9 9 9 9 4

What is wrong with my code?

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
90
91
92
93
#include<iostream>
#include<cstdlib>
using namespace std;

void merge(int arr[],int size,int low,int middle,int high){
     
     int temp[size];
     
     for(int i = low; i <= high; i++){
     
     temp[i] = arr[i];
             
     }
     
     int i = low;
     int j = middle+1;
     int k = low;
     
     while(i <= middle && j <= high){
             if(temp[i] <= temp[j]){
                        arr[k] = temp[j];
                        i++;           
                        
             }
             
             else{
                  arr[k] = temp[j];
                  j++;
                  
                  
             }
             
     k++;
             
             
     }



     while(i <= middle){
             arr[k] = temp[i];
             k++;
             i++;
                     
     }
     
     

}




void mergesort(int arr[],int size,int low,int high){
              
   if(low < high){
              
              int middle = (low + high)/2;
              mergesort(arr,size,low,middle);
              mergesort(arr,size,middle+1,high);
              merge(arr,size,low,middle,high);              
              
   }


}

int main(){
const int N = 50;    
int num[N];

for(int i =0; i < N; i++){
        
num[i] = rand()%10;
cout << num[i] << " ";        
        
}
cout << endl;
system("pause");
mergesort(num,N,0,N-2);

for(int i = 0; i < N; i++){

cout << num[i] << " ";        
        
}
cout << endl;    
    
    
system("pause");
return 0;    
    
}
Topic archived. No new replies allowed.