Search code examples
c++mergesort

mergesort in c++:segmentation fault


I am getting segmentation fault while implementing mergesort. I have checked for array out of bounds.I would love some help to find out where I have gone wrong.I have tried inputs for small arrays such as of size 10 where I have taken size of temp as static(>10).I have been pulling my hair out for hours.

UPDATE: I only needed to change mid=(low+high)/2.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

void merges(int arr[],int low,int mid,int high)
{
    int i=low,j=mid+1,k=0;
    int temp[high-low+1];
    while(i<=mid && j<=high)
    {
           if(arr[i]<arr[j])
            {
                temp[k++]=arr[i];
                i++;
            }
            else
            {
                temp[k++]=arr[j];
                j++;               
            }
    }
    if(i>mid)
    {
        while(j<=high)
        {
            temp[k++]=arr[j];
            j++;
        }
    }
    else
    {
        while(i<=mid)
        {
            temp[k++]=arr[i];
            i++;
        }
    }
    j=0;
    for(i=low;i<=high;i++)
    {
        arr[i]=temp[j++];    
    }
}

void mergesort(int arr[],int low,int high)
{
    if(low<high)
    {
    int mid=low+high/2;
    mergesort(arr,low,mid);
    mergesort(arr,mid+1,high);
    merges(arr,low,mid,high);
    }   
}

int main(){
    int n;
    cin >> n;
    int arr[n];
    for(int arr_i = 0;arr_i < n;arr_i++){
    cin >> arr[arr_i];
    }
    int i,j,k;
    mergesort(arr,0,n-1);
    for(i=0;i<n;i++)
        cout<<arr[i];
    return 0;
}

Solution

  • i only needed to change mid=(low+high)/2. Thank you @Gerado Gálvez for your suggestion