我有一个大小为A
的数组n
。我想将A
的元素重新排序到另一个数组B
中,以便A
中位于B
之间的元素首先在n = 9
中排序。例如,如果B
,则A[0]
的前两个元素应为A[8]
和A
,因为这些元素是B[2]
中最远的两个元素(距离8)。 A[4]
应为A[0]
,因为该元素距离A[8]
和B[3] = A[2]
(距离4)最远。接下来我们得到B[4] = A[6]
和A[2]
,因为A[6]
和A[0]
离A[4]
,A[8]
和A[1], A[3], A[5], A[7]
最远(最小值)距离2)。最后B
位于n
的最后四个位置(已经添加的元素的最小距离为1)。
执行此操作的快速算法是什么,处理任意大小的数组submit()
?
答案 0 :(得分:0)
这样的事情应该这样做: 您复制第一个元素。将数组的长度作为步长,并复制其奇数倍。将步长减半,然后重复,直到复制完所有元素(并且步长为1)。 在Java中实现它可能如下所示:
public static int[] farApartSort(int[] A) {
// Set up
int[] B = new int[A.length];
int i = 0;
// First value
B[i++] = A[0];
// Loop through the array in increments which halve each time
int chunkLength = A.length - 1;
do {
// Take the odd multiples of the current increment
for (int j = 1; chunkLength * j < A.length; j += 2) {
// Copy the values into the sorted array
B[i++] = A[chunkLength * j];
}
chunkLength /= 2;
} while (chunkLength > 0);
return B;
}