arrays - 先排列奇数,再排列偶数。奇偶顺序不应该改变

标签 arrays algorithm performance big-o

下面是代码片段,用于在不改变原始数组中偶数/奇数顺序的情况下,对奇数和偶数重新排序。

输入 - {1, 4, 8, 3, 9, 12, 7} 输出 - {1, 3, 9, 7, 4, 8, 12}

我们能否在空间上从 O(n2) 改进它(不使用额外空间)?

public  static void reOrder(int[] arr) {
     int evenIndex  = arr.length;
     for(int i=0; i < arr.length;i++) {
            if(arr[i] % 2 == 0 && evenIndex == arr.length) //even index
                evenIndex = i;

            else if( arr[i] % 2 != 0 ) {
                if(i > evenIndex ) {
                    shift (arr, evenIndex , i);
                    evenIndex ++;
                }
            }
     }
}

static void shift(int[] arr, int evenIndex, int endIndex) {
    int temp = arr[endIndex];
    for(int i = endIndex; i > evenIndex ;i --) {
        arr[i] = arr[i-1];
    }
    arr[evenIndex] = temp;
}

最佳答案

稳定的分区就是你要找的

std::vector<int> l = {1, 4, 8, 3, 9, 12, 7};
std::stable_partition(l.begin(), l.end(),
                      [](int A) -> bool {
                          return (A & 1) == 1; // A is odd
                      });

Exactly N applications of the predicate and O(N) swaps if there is enough extra memory. O(N log N) swaps and O(N) applications of the predicate

Question on how stable partition works along with its complexity.

例如,稳定的快速排序将在底层使用稳定的分区。查看已接受的答案 here用于复杂递归的稳定分区算法的 O(n*log(n)) 实现。

关于arrays - 先排列奇数,再排列偶数。奇偶顺序不应该改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50209060/

相关文章:

html - 指向 html 上的某些文件时,绝对路径和相对路径之间有区别吗?

javascript - 根据字符串路径生成div元素

java - 为什么这里会发生 ArrayIndexOutOfBoundsException?

python - 将多个 numpy 数组流式传输到一个文件

image - 特征向量划分

c++ - 交换数组的两个元素后计数反转

performance - 在SQLite中获取每个组的最后10行的有效方法

c++ - block 拼图求解C++算法

javascript - 无法使用 JavaScript/Node.js 映射两个数组

c++ - 如何找到不同子矩阵的数量?