+ 1

MergeSortApproach2 is giving stack over flow error

Why this is giving error plz explain https://code.sololearn.com/c8cH50siB4Fv/?ref=app

6th Jun 2022, 6:55 AM
Viraj
Viraj - avatar
1 Antwort
+ 1
in MergeSort() - because "operator precenence", end/2 was calculate first //int mid = start + end / 2; int mid = (start + end) / 2; - array part can started like mid..end of array //smallAns[0] = input[0]; smallAns[0] = input[start]; - this change is better (necessary) to get a size 1 element correctly //int part1[] = MergeSort( input, start, mid-1); int part1[] = MergeSort( input, start, mid); //int part2[] = MergeSort( input, mid, input.length-1); int part2[] = MergeSort( input, mid + 1, end); - There is a concept conflict ie. return array of size 1 if (start == end) { int [] smallAns = new int [1]; but the merge() returns the entire input array of fixed size like part1 [6] + part2 [6] = 12 size, it attempts merged 12 elements into the input[6] Instead of a large rewrite of the code I do: static int[] MergeArrays(int input[], int part1[], int part2[]) { int i=0, j=0, k=0; input = new int[part1.length + part2.length]; //added - then in main() print it like // MergeSort(input, 0, input.length); input = MergeSort(input, 0, input.length-1); PrintArray(input);
10th Jun 2022, 8:36 AM
zemiak