Java 我的mergesort代码中的merge函数有什么问题?
对不起,这里是初学者。这是我现在有的:Java 我的mergesort代码中的merge函数有什么问题?,java,mergesort,Java,Mergesort,对不起,这里是初学者。这是我现在有的: public class MergeSort { public static void main(String[] args) { int[] arr = {3, 5, 2, 4, 1}; sort(arr, 0, arr.length - 1); for(int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " ");
public class MergeSort
{
public static void main(String[] args)
{
int[] arr = {3, 5, 2, 4, 1};
sort(arr, 0, arr.length - 1);
for(int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
}
private static void sort(int[] arr, int lo, int hi)
{
if(lo >= hi)
{
return;
}
int mid = (lo + hi)/2;
sort(arr, lo, mid);
sort(arr, mid + 1, hi);
int size = hi - lo + 1;
int[] temp = new int[size]; //new array to merge into
merge(arr, temp, lo, mid + 1, hi);
for(int i = 0; i < size; i++)
{
arr[i + lo] = temp[i];
}
}
private static void merge(int[] arr, int[] temp, int lower, int mid, int upper)
{
int tempIndex = 0;
int leftLo = lower;
int leftHi = mid - 1;
int rightLo = mid;
int rightHi = upper;
while(leftLo <= leftHi && rightLo <= rightHi)
{
if(arr[leftLo] < arr[rightLo])
{
temp[tempIndex] = arr[leftLo];
tempIndex++;
leftLo++;
}
else
{
temp[tempIndex] = arr[rightLo];
tempIndex++;
rightLo++;
}
}
}
}
公共类合并排序
{
公共静态void main(字符串[]args)
{
int[]arr={3,5,2,4,1};
排序(arr,0,arr.length-1);
对于(int i=0;i=高)
{
返回;
}
int mid=(低+高)/2;
排序(arr、lo、mid);
排序(arr、mid+1、hi);
int size=hi-lo+1;
int[]temp=new int[size];//要合并到的新数组
合并(arr、temp、lo、mid+1、hi);
对于(int i=0;i 而在merge
中(leftLo),只要leftLo
和rightLo
都还没有达到它们的限制,就可以复制值。通常其中一个到达得很早。然后需要复制另一个的剩余值。可以通过添加以下两个循环来复制剩余的元素:
while (leftLo <= leftHi) {
temp[tempIndex] = arr[leftLo];
tempIndex++;
leftLo++;
}
while (rightLo <= rightHi) {
temp[tempIndex] = arr[rightLo];
tempIndex++;
rightLo++;
}
while(leftLo)您正在尝试执行递归吗?
private static void merge(int[] arr, int[] temp, int lower, int mid, int upper) {
int tempIndex = 0;
int leftLo = lower;
int leftHi = mid - 1;
int rightLo = mid;
int rightHi = upper;
while (leftLo <= leftHi && rightLo <= rightHi) {
if (arr[leftLo] < arr[rightLo]) {
temp[tempIndex] = arr[leftLo];
tempIndex++;
leftLo++;
} else {
temp[tempIndex] = arr[rightLo];
tempIndex++;
rightLo++;
}
}
while (leftLo <= leftHi) {
temp[tempIndex] = arr[leftLo];
tempIndex++;
leftLo++;
}
while (rightLo <= rightHi) {
temp[tempIndex] = arr[rightLo];
tempIndex++;
rightLo++;
}
}