I dont know whats wrong with this code but ive spend way too much time to figure out the problem but still couldnt, I think there is some error with the copying of array because every other thing seems to be correct
please check this code-
#include<iostream>
using namespace std;
void MergeArray(int arr[],int lb,int mid,int ub){
int i=lb;
int j=mid+1;
int k=0;
int newarr[ub-lb+1];
//condition required for comparison between the split parts
while(i<=mid && j<=ub){
if(arr[i] < arr[j]){
newarr[k]=arr[i];
k++;
i++;
}
//basically a[j]<a[i] in this else condition
else{
newarr[k]=arr[j];
k++;
j++;
}
}
//all th left out elements in a[i] when a[j] is finished are added to newarr
while(i<=mid){
newarr[k]=arr[i];
k++;
i++;
}
//all th left out elements in a[j] when a[i] is finished are added to newarr
while(j<=ub){
newarr[k]=arr[j];
k++;
j++;
}
//copying all the elements of newarr to original arr
//i think this part has something messed up
for(int i=lb;i<=ub;i=i+1){
arr[i]= newarr[i];
}
}
void MergeElements(int arr[], int lb,int ub){
int mid;
if(lb<ub){
mid=(lb+ub)/2;
//spliting into 2 arts**
MergeElements(arr,lb,mid);
MergeElements(arr,mid+1,ub);
//merging in sorted order**
MergeArray(arr,lb,mid,ub);
}
}
int main(){
int n;
cout<<"enter the size of the array"<<endl;
cin>>n;
int arr[n];
cout<<"please enter the elements of the array"<<endl;
for(int i=0;i<n;i++){
cout<<"enter the element no."<<i<<endl;
cin>>arr[i];
}
MergeElements(arr,0,n-1);
cout<<"\tSorted Array Elements"<<endl;
for(int i=0;i<n;i++){
cout<<arr[i]<<"\t";
}
return 0;
}
i think i am not able to get the array correctly because everything else seems to be correct according to me please check