重新排序数组,以便首先排序远离的元素

时间:2015-05-02 10:25:11

标签: algorithm sorting

我有一个大小为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()

1 个答案:

答案 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;

}

相关问题