2

I am trying to implement Merge sort algorithm from (Introduction to Algorithms (CLRS)) using a vector in c++ but the vector is not sorting, please help, where am i going wrong, I am trying to use call by refference
The input is from a text file which contains integers in new line

#include <iostream>
#include <fstream>
#include <vector>
#include <limits>

using namespace std;

void merge(vector<long>& A, long high, long mid, long low)
{
     long n1,n2;
    n1 = mid -low +1;
    n2 = high - mid;

vector<long> L; //auxilarry array
vector<long> R; //auxilarry array

for(int i = low; i <= mid;i++)
{
    L.push_back(A[i]);
}

for(int i = mid+1; i <= high;i++)
{
    R.push_back(A[i]);
} 

L.push_back(numeric_limits<int>::max()); 
R.push_back(numeric_limits<int>::max());

int i = 0, j = 0;

for(int k = low; k <= high; k++)
{
    if(L[i]<=R[j])
    {
        A[k] = L[i];
        i++;
    }
    else
    {
        A[k] = R[j];
        j++;
    }
}

}
void mergeSort(vector<long>& A, long low, long high)
{
long mid;

if(low < high)
{
    mid = (high+low)/2 ;

    mergeSort(A,low,mid);
    mergeSort(A, mid+1,high);
    merge(A,low, mid,high);
 }
}

int main()
{
ifstream fin("Array.txt");

vector<long> array;

for(long i;fin>>i;)
{
    array.push_back(i);
}
cout<<array.size();
mergeSort(array,0,array.size());

for(long i=0;i<array.size();i++)
{
    cout<<array[i]<<endl;
}

return 0;
}
Nirban
  • 33
  • 6

1 Answers1

3

your merge function is declared as :

void merge(vector<long>& A, long high, long mid, long low)

and u are calling merge inside mergesort by.

void merge(array, low, mid, high)

Ordering of arguments is wrong. See low and high variable ordering

pseudo_teetotaler
  • 1,485
  • 1
  • 15
  • 35
  • Can you please take a look https://stackoverflow.com/questions/71178163/clrs-solution-seems-meaningless-as-one-line-make-me-skeptical – Encipher Feb 19 '22 at 00:14