在Java中实现递归MergerSort
我在Java中实现合并排序时遇到问题。目标是有两个类,第一个是union,它组合了两个已经排序的数组(我想我正确地得到了这一个)。然而,另一个类“sort”是我真正陷入困境的地方。我想递归地将一个数组拆分为更小的数组,然后将它们与union组合。这是我到目前为止得到的,我希望有人能帮助我。。。谢谢在Java中实现递归MergerSort,java,recursion,mergesort,Java,Recursion,Mergesort,我在Java中实现合并排序时遇到问题。目标是有两个类,第一个是union,它组合了两个已经排序的数组(我想我正确地得到了这一个)。然而,另一个类“sort”是我真正陷入困境的地方。我想递归地将一个数组拆分为更小的数组,然后将它们与union组合。这是我到目前为止得到的,我希望有人能帮助我。。。谢谢 class MergeSort { public static int[] sort(int[] array) { int[] firsthalf = new int[array.length];
class MergeSort {
public static int[] sort(int[] array) {
int[] firsthalf = new int[array.length]; #muss noch verschoben werden, a
System.arraycopy(array, 0, firsthalf, 0, array.length);
int[] firsthalf = Arrays.copyofRange(firsthalf, 0, lefthalf.length/2)
int[] secondhalf= Arrays.copyofRange(
public static int[] union(int[] sortedIntArray1,
int[] sortedIntArray2) {
int[] neuesarray = new int[sortedIntArray1.length + SortedIntArray2.length];
int i = 0, j = 0, k = 0;
while (i < sortedIntArray1.length && j < sortedIntArray2.length)
{
if (sortedIntArray1[i] < sortedIntArray2[j]) #wenn liste an stelle i kleiner als liste 2 an stelle j
{
neuesarray[k] = sortedIntArray1[i];
i++;
}
else
{
answer[k] = sortedIntArray2[j]; #bei umgekehrtem fall, wird von liste2 das element angehängt
j++;
}
k++;
}
while (i < sortedIntArray1.length) #diese while schleifen sind wichtig, sonst bleibt der Zeiger praktisch stehen
{
neuesarray[k] = sortedIntArray1[i];
i++;
k++;
}
while (j < sortedIntArray2.length)
{
neuesarray[k] = sortedIntArray2[j];
j++;
k++;
}
return neusarray;
}
}
}
类合并排序{
公共静态int[]排序(int[]数组){
int[]firsthalf=new int[array.length];#muss noch verschoben werden,a
数组复制(数组,0,上半部分,0,数组.长度);
int[]firsthalf=Arrays.copyofRange(firsthalf,0,lefthalf.length/2)
int[]secondhalf=Arrays.copyofRange(
公共静态int[]并集(int[]排序数据集1,
int[]数字塔雷2){
int[]neuesarray=新int[sorteddintarray1.length+sorteddintarray2.length];
int i=0,j=0,k=0;
而(i
else{answer[k]=sortedIntArray2[j];#bei umgekehrtem fall,wird von listed2 das element angehängt j++}回答[k]的目的是什么?当sortedIntArray1[i]=sortedIntArray2[j]时会发生什么?@SkyDream他在回答[k]中保留了这些值。但是,我不知道这些值有什么用呢