mardi 3 novembre 2020

Merge sort of array in c++? [duplicate]

I am practicing merge sort using merge sort on array of strings. I want to declare all variable in the .h but when I do my program didn't work out.

#include <iostream>
#include <list>
#include <string>
using namespace std;

void MergeSortA(int low , int high);
void MergeA(int low ,int mid ,int high);

string currentArray[5];
int main()
{
    for(int i = 0; i < 5; i++)
        cin >> currentArray[i];

    MergeSortA(0,4);

    for(int i = 0; i < 5; i++)
        cout << currentArray[i] <<endl;

    return 0;
}

void MergeSortA(int low , int high)
{
    int mid = 0;
    if(low < high)
    {
        mid = ((low+high)/2);
        MergeSortA(low , mid);
        MergeSortA(mid+1,high);
        MergeA(low,mid,high);
    }
}
void MergeA(int low ,int mid , int high)
{
    int i = low, j = mid+1 , k = low;
    string Temp[5];

    while(i <= mid && j <= high)
    {
        if( currentArray[i] < currentArray[j] )
        {
            Temp[k].assign(currentArray[i]);
            i++;
        }
        else
        {
            Temp[k].assign(currentArray[j]);
            j++;
        }
        k++;
    }
    if(i > mid )
    {
        for(int h = j ;h <= high ; h++ )
        {
            Temp[k].assign(currentArray[h]);
            k++;
        }
    }
    else
        for(int h = i; h<= mid ; h++ )
        {
            Temp[k].assign(currentArray[h]);
            k++;
        }
   for(int i = 0; i <= high ; i++)
   {
       currentArray[i].assign(Temp[i]);
   }
}

The problem I am facing is that

void MergeSortA(int low , int high)
    {
        int mid = 0;
        if(low < high)
        {
            mid = ((low+high)/2);
            MergeSortA(low , mid);
            MergeSortA(mid+1,high);
            MergeA(low,mid,high);
        }
    }

I declare the "mid" in the .h file then I ran the program and it didn't sort the list.

.h file

int mid;

.cpp

 void MergeSortA(int low , int high)
        {
            mid = 0;
            if(low < high)
            {
                mid = ((low+high)/2);
                MergeSortA(low , mid);
                MergeSortA(mid+1,high);
                MergeA(low,mid,high);
            }
        }

Aucun commentaire:

Enregistrer un commentaire