import java.util.* ;
import java.io.*;
public class Main {
public static void merge(int[]arr,int low,int mid,int high){
int temp [] = new int[high+1];
int index=0;
int left = low;
int right = mid+1;
while(left<=mid && right<=high)
{
if(arr[left]<=arr[right]){
temp[index]=arr[left];
left++;
}
else{
temp[index]=arr[right];
right++;
}
index++;
}
//for exhaustion of any of the parts
while(left<=mid){
temp[index]=arr[left]; left++; index++;
}
while(right<=high){
temp[index]=arr[right]; right++; index++;
}
//copying elements to array
for(int i=0; i<temp.length; i++){
arr[i]=temp[i];
}
//printing arr
for(int i=0; i<temp.length; i++){
System.out.print(arr[i]+" ");
}
}
public static void mergesort(int[]arr,int low,int high)
{
//base case
if(low>=high){
return;
}
int mid = (low+high)/2;
mergesort(arr,low,mid);
mergesort(arr,mid+1,high);
merge(arr,low,mid,high);
}
public static void main(String[] args)
{
int[] arr = {2,3,46,5,8,7,6};
int n = arr.length;
mergesort(arr,0,n-1);
}
}
我使用递归实现了合并排序,请帮助确定我的代码有什么问题?它给出前三个元素排序然后一些 0,然后再次排序元素然后未排序。
递归无法正常工作并给出排序的数组结果,为什么?
尝试此修复(可能还有其他问题):
int temp [] = new int[high-low+1];
//copying elements to array
for(int i=0; i<temp.length; i++){
arr[i]=temp[i];
}
从
0
而不是 low
开始复制回原始数组。并且还复制所有 temp
,而不仅仅是您在调用期间填充的部分。