vendredi 24 juillet 2020

I'm getting a runtime error in this code. This code is for the merge sort algorithm. As I'm a beginner please help me

I'm getting a runtime error in this code. This code is for the merge sort algorithm. As I'm a beginner please help me in finding the error. This code uses recursions and functions. The function mergesort is called recursively to divide the array till its size is reduced to 1. Then multiple arrays are merged using the merge function.

 #include <iostream>
    using namespace std;
    void merge(int l[],int size1,int r[],int size2,int input[],int size){
        int i=0,j=0,k=0;
        while(i<size1 && j<size2){
            if(l[i]<=r[j]){
                input[k]=l[i];
                k++;
                i++;
            }
            else{
                input[k]=r[j];
                j++;
            }
            k++;
        }
        while(i<size1){
            input[k]=l[i];
            i++;
            k++;
        }
        while (j<size2){
            input[k]=r[j];
            j++;
            k++;
        }
    }
    void mergesort(int input[],int size){
        if(size<2){
            return;
        }
        int mid= size/2;
        int l[500];
        int r[500];
        for(int i=0;i<mid-1;i++){
            l[i]=input[i];
        }
        for(int j=mid;j<size-1;j++){
            r[j-mid]=input[j];
        }
        mergesort(l,mid);
        mergesort(r,size-mid);
        merge(l,mid,r,size-mid,input,size);
    
    
    }
    
    int main() {
        int n;
        cin>>n;
        int arr[1000];
        for(int i=0;i<n;i++){
            cin>>arr[i];
        }
        mergesort(arr,n);
        for(int j=0;j<n;j++){
            cout<<arr[j]<<" ";
        }
    
    
        return 0;
    }

Aucun commentaire:

Enregistrer un commentaire