I am trying to sort an array of strings using a merge sort algorithm. I wrote this code and works for arrays of integers, but it is surprising that this is not the case with an array of strings. It seems to just sort the second part of the array. I donβt know what is wrong with this code! I will be grateful 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]); } }
Zhape source share