I have been trying to remove the error in this code from last few days now. I have done everything that I possibly could have. Please help!!!. Basically this code uses vectors of C++ stl and passes the vector in a method called mergeSort which recurrsively calls itself over two parts of the vector and then calls another function which merges these parts and stores the value in a temporary vector called Temp. In the end this function copies the temp vector back into the old vector. And main does the rest.
The problem is that the old vector only shows few elements as sorted and marks the rest part as 0. It appears that it didnt copy the correct values from temp vectors or temp vector didnt had the desired values at first place.
“
type here
// Below is the entire code –
#include<bits/stdc++.h>
using namespace std;
class Solution{
public:
void merge(vector<int> &vect, int begin, int mid, int end){
vector<int> temp;
int i=begin;
int j=mid+1;
while(i<=mid && j<=end)
{
if(vect.at(i)<=vect.at(j)){
temp.push_back(vect.at(i));
i++;
}
else{
temp.push_back(vect.at(j));
j++;
}
}
while(i<=mid){
temp.push_back(vect.at(i));
i++;
}
while(j<=end){
temp.push_back(vect.at(j));
j++;
}
for(int k=0; k<=end; k++){
vect.push_back(temp.at(k));
}
}
void mergeSort(vector<int>&vect, int begin, int end){
if(begin>=end)
return;
int mid = (begin+end)/2;
mergeSort(vect, begin, mid);
mergeSort(vect, mid+1, end);
merge(vect, begin, mid, end);
}
};
int main(){
int n;
cin>>n;
vector<int> vect;
for(int i=0; i<n; i++)
{
int val;
cin>>val;
vect.push_back(val);
}
Solution s;
s.mergeSort(vect, 0, n-1);
for(int i=0; i<n; i++)
cout<<vect.at(i);
return 0;
}