gpt4 book ai didi

java - 如何在java中将数组分成两半

转载 作者:行者123 更新时间:2023-11-30 08:15:25 24 4
gpt4 key购买 nike

我需要在排序后拆分这个数组,以便打印类似的内容

答:[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;

}
}

最佳答案

要使其动态化,请根据数组长度进行操作并将其分成两部分:

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));

希望对您有所帮助。

关于java - 如何在java中将数组分成两半,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28887966/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com