+ 1

help me to fix this merge sort code in c++

what is the problem with this code and how can i fix it ? ******************************* #include "stdafx.h" #include <iostream> using namespace std; // merge the two halves into a sorted array void Merge(int *a, int from, int to, int mid) { int i = from; int j = mid + 1; int k = 0; int temp[to - from + 1]; // merge the two parts into temp[] while (i <= mid && j <= to) { if (a[i] < a[j]) { temp[k] = a[i]; k++; i++; } else { temp[k] = a[j]; k++; j++; } } // insert all the remaining values from i to mid into temp[] while (i <= mid) { temp[k] = a[i]; k++; i++; } // insert all the remaining values from j to to into temp[] while (j <= to) { temp[k] = a[j]; k++; j++; } // assign sorted data stored in temp[] to a[] for (i = from; i <= to; i++) { a[i] = temp[i - from]; } } void MergeSort(int *a, int from, int to) { int mid; if (from < to) { mid = (from + to) / 2; MergeSort(a, from, mid); MergeSort(a, mid + 1, to); Merge(a, from, to, mid); } } int main() { int n = 10; // number of elements int arr[10] = { 10, 54, 63, 6, 420, 11, 41, 32, 17, 22 }; MergeSort(arr, 0, n - 1); // print the array for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0; } ********************** the vs2017 say that the error is at line 9 int temp[to - from + 1]; the error is with " to " expression must have a constant value

29th Apr 2018, 7:03 PM
MeDoXs
MeDoXs - avatar
2 Réponses
+ 2
Yes, the value inside [here] must be known before the program runs. You can use a std::vector or change it to: int* temp = new int[to - from + 1]; But you must delete[] the int* when you don't need it anymore.
29th Apr 2018, 10:06 PM
Timon Paßlick
0
#include <iostream> using namespace std; // merge the two halves into a sorted array void Merge(int *a, int from, int to, int mid) { int i = from; int j = mid + 1; int k = 0; int temp[to-from+1]; // merge the two parts into temp[] while (i <= mid && j <= to) { if (a[i] < a[j]) { temp[k] = a[i]; k++; i++; } else { temp[k] = a[j]; k++; j++; } } // insert all the remaining values from i to mid into temp[] while (i <= mid) { temp[k] = a[i]; k++; i++; } // insert all the remaining values from j to to into temp[] while (j <= to) { temp[k] = a[j]; k++; j++; } // assign sorted data stored in temp[] to a[] for (i = from; i <= to; i++) { a[i] = temp[i-from]; } } void MergeSort(int *a, int from, int to) { int mid; if (from < to) { mid=(from+to)/2; MergeSort(a, from, mid); MergeSort(a, mid+
20th Oct 2019, 3:19 AM
Megan McGuire
Megan McGuire - avatar