I'm trying to implement a mergesort algorithm which is not working properly. Merge Sort works as follows:
i. Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted).
ii. Repeatedly merge sublists to produce newly sorted sublists until there is only 1 sublist remaining. This will be the sorted list. The implementation is provided below.
Initially, this method is called recursively till there will be only one element.
public void mergeSort(int low, int high) {
if (low >= high) {
return;
}
int middle = (low + high) / 2;
// recursion for the merge
mergeSort(low, middle);
mergeSort(middle + 1, high);
merge(low, middle, high);
}
This is the merge method provided.
private void merge(int low, int middle, int high) {
int i = low, j = middle;
int index = low;
for (int k = 0; k <= high; k++) {
tempArray[k] = nums[k];
}
/*
Copy the smallest values from either the left
or the right side back to the original array
*/
while ((i <= middle) && (j <= high)) {
if (tempArray[i] <= tempArray[j]) {
nums[index++] = tempArray[i++];
} else {
nums[index++] = tempArray[j++];
}
}
// fill the left side of the array
while (i < middle) {
nums[index++] = tempArray[i++];
}
// fill the right side of the array
while (j < high) {
nums[index++] = tempArray[j++];
}
}
What is the issue here?
The input is int[] arr = {12, 3, 4, 56, -7, 1};
and the output is 12 12 12 12 56 56
I modified the merge function and it starts to work now. Especially, the j
needs to be initialized after the middle term j = middle+1
private void merge(int low, int middle, int high) {
int i = low, j = middle+1;
int index = low;
for (int k = 0; k <= high; k++) {
tempArray[k] = nums[k];
}
/*
Copy the smallest values from either the left
or the right side back to the original array
*/
while ((i <= middle) && (j <= high)) {
if (tempArray[i] <= tempArray[j]) {
nums[index++] = tempArray[i++];
} else {
nums[index++] = tempArray[j++];
}
}
// fill the left side of the array
while (i <= middle) {
nums[index++] = tempArray[i++];
}
// fill the right side of the array
while (j <= high) {
nums[index++] = tempArray[j++];
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.