给定数组中的数字序列,返回交替排列的这些数字,即最小数字,后跟最多数字,接着是第二个最低数字,接着是第二个最高数字,依此类推。
输入:1 2 3 4 5 输出:1 5 2 4 3
输入:10 5 7 9 2 2 输出:2 10 2 9 5 7
我尝试这样的事情,但不适合我,可以帮助我。 我需要两个输出到同一个函数或方法。
public class Test { int [] inputArray = {1,2,3,4,5};
void mergeSort(int[] array) {
int[] helper = new int[array.length];
mergesort(array, helper, 0, array.length - 1);
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
private void mergesort(int[] array, int[] helper, int low, int high) {
if (low < high) {
int middle = (low + high) / 2;
mergesort(array, helper, low, middle);
mergesort(array, helper, middle + 1, high);
merge(array, helper, low, middle, high);
}
}
private void merge(int[] array, int[] helper, int low, int middle, int high) {
for (int i = low; i <= high; i++) {
helper[i] = array[i];
}
int helperLeft = low;
int counter = 0;
int helperRight = middle + 1;
int current = low;
while (helperLeft <= middle && helperRight <= high) {
if (counter % 2 == 0) {
if (helper[helperLeft] <= helper[helperRight]) {
array[current] = helper[helperLeft];
helperLeft++;
} else {
array[current] = helper[helperRight];
helperRight++;
}
} else {
if (helper[helperLeft] >= helper[helperRight]) {
array[current] = helper[helperLeft];
helperLeft++;
} else {
array[current] = helper[helperRight];
helperRight++;
}
}
counter++;
current++;
}
int remaining = middle - helperLeft;
for (int i = 0; i <= remaining; i++) {
array[current + i] = helper[helperLeft + i];
}
}
public static void main(String[] args) {
Solution i = new Solution();
i.mergeSort(i.inputArray);
}
}
输出:1,4,3,5,2
答案 0 :(得分:2)
我首先将数组排序为正常,然后使用它以您想要的方式进行交替。
int[] toReturn = new int[inputArray.length];
Arrays.sort(inputArray);
for (int i = 0; i < inputArray.length; i+=2) {
toReturn[i] = inputArray[i/2];
}
for (int i = 1; i < inputArray.length; i+=2) {
toReturn[i] = inputArray[inputArray.length - i/2 - 1];
}
答案 1 :(得分:0)
您可以简单地对数组进行排序,然后执行此操作:
i = 0
和j = array.length - 1
j > i
然后打印array[i]
后跟array[j]
i
并减少j
array[i]
(处理i == j
时的情况)以下是示例代码:
Arrays.sort(array);
int i = 0, j = array.length - 1;
while (i < j) {
System.out.print(array[i] + " ");
System.out.print(array[j] + " ");
i++;
j--;
}
if (i == j) {
System.out.println(array[i]);
}