this is the code for merge sort and sometimes it gives the right output but sometimes it gives output where one value is changed .
#include "bits/stdc++.h"
using namespace std;
//function to merge two array
vector<int> merging(vector<int> a,vector<int> b){
int x = (int)a.size() + (int)b.size();
vector<int> v(x);
int p = 0;
int q = 0;
for(int i=0;i<x;++i){
if((q<(int)b.size())?a[p]<b[q]:true && p<(int)a.size()){
v[i] = a[p];
p++;
}else{
v[i] = b[q];
q++;
}
}
return v;
}
//splitting the array and then merging the array
vector<int> mergeSort(vector<int> k){
int x = (int)k.size();
if(x<2){
return k;
}
vector<int> a(k.begin(),k.begin()+(x/2));
vector<int> b(k.begin()+(x/2),k.end());
return merging(mergeSort(a),mergeSort(b));
}
int main(){
vector<int> v = {3,5,34,11,32,7,35,54,67,89,23,4,3};
//calling the merge function
vector<int> b = mergeSort(v);
for(int i=0;i<(int)b.size();++i){
cout << b[i] << "\n";
}
return 0;
}
sometime output is expected 3 3 4 5 7 11 23 32 34 35 54 67 89
sometime output is 3 3 4 5 7 11 23 32 34 -423887504 35 54 67