我需要在对数组进行排序后将其拆分,以便打印类似
的数组A:[8,7,6,5]
B:[4,3,2,1]
我知道这可能很简单,但我无法弄明白。我需要做x.length / 2这样的事情吗?
import java.util.Arrays;
public class RecursiveMerge
{
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] x= {8,7,5,6,2,4,3,1};
System.out.println(Arrays.toString(x));
System.out.println(Arrays.toString(mergeSort(x)));
}
public static int [] mergeSort (int []a)
{
if(a.length ==1)
return a;
else
{
int mid = a.length/2;
int [] left =mergeSort(Arrays.copyOfRange(a, 0 , mid ));
int [] right =mergeSort(Arrays.copyOfRange(a, mid, a.length ));
mergeSort(left);
mergeSort(right);
return merge (left, right);
}
}
public static int[] merge (int[] left, int[] right)
{
int [] result = new int [left.length + right.length];
int leftPtr=0, rightPtr=0, resultPtr=0;
while(leftPtr < left.length && rightPtr < right.length)
if (left[leftPtr] < right [rightPtr])
result[resultPtr++] = left[leftPtr++];
else
result[resultPtr++] = right[rightPtr++];
while (leftPtr < left.length)
result[resultPtr++] = left[leftPtr++];
while (rightPtr <right.length)
result[resultPtr++] = right[rightPtr++];
return result;
}
}
答案 0 :(得分:3)
要动态制作,请根据数组长度进行分割并将其拆分为两个:
int [] x= {8,7,5,6,2,4,3,1};
int len = x.length;
int a[] = Arrays.copyOfRange(mergeSort(x), 0, len/2);
int b[] = Arrays.copyOfRange(mergeSort(x), (len/2), len);
System.out.println("A: " + Arrays.toString(a));
System.out.println("B: " + Arrays.toString(b));
希望它有所帮助。