I am trying to sort an array of strings using merge sort algorithm.I wrote this code and it works for arrays of integers but surprisingly for array of strings does not!It seems that it just sorts second part of array.I have no idea what piece is wrong in this code! I will be appreciated for your help.
#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]);
}
}
You need a correction while copying values back into currentArray from the Temp array: