0
#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!

  • 2
    Your [`main` function](http://en.cppreference.com/w/cpp/language/main_function) is invalid. And please read [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) Lastly, please [learn how to debug your programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Some programmer dude Apr 22 '18 at 12:48
  • @Someprogrammerdude Both of the things you have stated are completely irrelevant to my question Secondly code was incorrect logically and had nothing to do with debugging.. – Daksh Sharma Apr 22 '18 at 12:57
  • Debugging is *the* way to find logical errors (most other errors are found by the compiler itself). If you step through the code in a debugger, line by line, while monitoring variables and their values you should have easily been able to find the problem. And while the other two points are not relevant to the problem itself, they *are* two important things you should consider. In fact, not declaring the `main` function correctly technically makes your program invalid. – Some programmer dude Apr 22 '18 at 14:38

1 Answers1

0

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];
}
ilim
  • 4,477
  • 7
  • 27
  • 46
Anton Todua
  • 667
  • 4
  • 15