Merge sorting by array of strings

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]); } } 
+4
source share
1 answer

You need correction when copying values ​​back to currentArray from the Temp array:

 for(int i = low; i <= high ; i++) //copy from low to high { currentArray[i].assign(Temp[i]); } 
+2
source

Source: https://habr.com/ru/post/1448023/


All Articles