user11555625
user11555625

Reputation:

My C++ Merge Sort code isn't working. What am i missing here?

In my code , lb refers to lower bound and ub refers to upper bound.I'm using the mergeSort function to recursively split the array into smaller pieces and the merge function to merge in their sorted order.

#include <iostream>
using namespace std;

void merge(int input[], int lb, int ub, int size)
{
    int i = lb;
    int k = 0;
    int mid = (lb + ub) / 2;
    int j = mid + 1;

    int *arr = new int[size];

    while (i <= mid && j <= ub)
    {
        if (input[i] <= input[j])
            arr[k++] = input[i++];
        else
            arr[k++] = input[i++];
    }
    while (i <= mid)
        arr[k++] = input[i++];
    while (j <= ub)
        arr[k++] = input[j++];

    for (k = 0; k < size; k++)
        input[k] = arr[k];
}
void mergeSort(int input[], int size)
{
    int lb = 0;
    int ub = size - 1;
    int mid;
    if (size == 0)
    {
        return;
    }
    else if (lb < ub)
    {
        mid = (lb + ub) / 2;
        mergeSort(input, mid - lb + 1);
        mergeSort(input + mid + 1, ub - mid);
        merge(input, lb, ub, size);
    }
    else
    {
        return;
    }
}

int main()
{
    int input[1000], length;
    cin >> length;
    for (int i = 0; i < length; i++)
        cin >> input[i];
    mergeSort(input, length);
    for (int i = 0; i < length; i++)
    {
        cout << input[i] << " ";
    }
}

Upvotes: 2

Views: 77

Answers (1)

Zig Razor
Zig Razor

Reputation: 3495

You have used i istead of j in the first while loop in merge function. The correct code is the following

while (i <= mid && j <= ub) { 
        if (input[i] <= input[j]) 
           arr[k++] = input[i++]; 
       else 
           arr[k++] = input[j++];     
}

Upvotes: 2

Related Questions