I read the theory of merge sort algorithm and based on that i wrote an implementation of merge sort in C++ using the STL Vector class.
I know that a copy paste from any one of the trillion articles on internet about merge sort can solve this, but I wanted to try this one on my own.
When I run the code i get segmentation fault core dumped error, which is caused by the recursive functions not terminating. Can anybody help me find the error in the code.
#include<iostream>
#include<vector>
void merge(std::vector<int>& arr,int last,int begin,int mid);
void mergeSort(std::vector<int>& arr,int begin, int last){
std::cout<<"In merge sort";
int mid;
if(begin<last){
mid = (begin+last)/2;
mergeSort(arr,begin,mid);
mergeSort(arr,mid,last);
merge(arr,last,begin,mid);
}
return;
}
void merge(std::vector<int>& arr ,int last,int begin,int mid){
if(last==begin){
std::cout<<"Returned form finger";
return;
}
int b=begin,c=mid;
std::vector<int> temp;
while(b<mid&&c<last){
if(arr[b]<arr[c]){
temp.push_back(arr[b]);
b++;
}
else{
temp.push_back(arr[c]);
c++;
}
}
while(b<mid){temp.push_back(arr[b]);}
while(c<last){temp.push_back(arr[c]);}
arr.swap(temp);
return;
}
int main(){
std::vector<int> arr({2,4,1,5,3,6,2,4,3});
for(auto it=arr.begin();it!=arr.end();++it){
std::cout<<*it<<' ';
}
std::cout<<'\n';
mergeSort(arr,0,8);
for(auto it=arr.begin();it!=arr.end();++it){
std::cout<<*it<<' ';
}
return 0;
}
I use gcc version 9.3.0 to compile the code using the terminal command
$ gcc filename.cpp -lstdc++
After analyzing the code i think the problem is in the merge function but i cant point out where it is. It would be helpful if anybody could help me and if possible suggest a few ways to optimize my code.