Search code examples
c++algorithmmergesort

Getting wrong results for merge sort if i change index variable to zero and k=0 in merge function


#include<bits/stdc++.h>
#define size 100
using namespace std;
void merge(int a[],int,int,int);
void merge_sort(int a[],int,int);
main(){
    int a[size],i,n;
    cout<<"Enter the no  of elements in the array: ";
    cin>>n;
    for(i=0;i<n;i++){
        cin>>a[i];
    }
    merge_sort(a,0,n-1);
    cout<<"\nThe sorted array is: ";
    for(i=0;i<n;i++){
        cout<<a[i]<<"  ";
    }
}
void merge(int a[],int l,int m,int r){
    int i=l,j=m+1,index=1,temp[size],k;//HERE
    while((i<=m) && (j<=r)){
        if(a[i]<a[j]){
            temp[index]=a[i];
            i++;
        }
        else{
            temp[index]=a[j];
            j++;
        }
        index++;
    }
    if(i>m){
        while(j<=r){
            temp[index]=a[j];
            j++;
            index++;
        }
    }
    else{
        while(i<=m){
            temp[index]=a[i];
            i++;
            index++;
        }
    }
    for(k=1;k<index;k++){//HERE
        a[k]=temp[k];
    }
}

void merge_sort(int a[],int l,int r){
    int m;
    if(l<r){
        m=(l+r)/2;
        merge_sort(a,l,m);
        merge_sort(a,m+1,r);
        merge(a,l,m,r);
    }
}


for example if n=5
input: 5 8 7 1 4
output: 1 4 5 7 8
but if k=0 and index=0
output is 1 1 4 4 8
All i am doing is accessing temp array and array a which is argument of function merge from index zero.
In case of taking index and k=1 why is array a not overflowing.
Any insight would be helpful.Thank You!


Solution

  • The problem is in the way you copy values from temp to a. A correct code should looks like this (index should starts from 0):

    for(k=0;k<index;k++){//HERE
        a[l+k]=temp[k];
    }