连续排序数组

mar*_*who 1 java arrays sorting object

我有一个用户给我一个随机数组的对象,我想做一些错误检查,基本上我希望空对象在数组的末尾,以便数组的中间只由非null组成对象(对象的排序无关紧要).

这是我拥有的,它不起作用.谁能请帮忙.

private void properArray(){
    int i = 0;
    int j;
    int cap = theHeap.length;
    for(; i < (cap-1); i++){
        if (theHeap[i] == null){
            j = i + 1;
            while(j < (cap-1)){
                if(theHeap[j] != null){
                    theHeap[i] = theHeap[j];
                    theHeap[j] = null;
                }
                j++;  
            }
        }
    } 
}
Run Code Online (Sandbox Code Playgroud)

Luk*_*der 8

以下是一种更简单的方法,可以对这样的数组进行排序:

Arrays.sort(theHeap, new Comparator() {
  public int compare(Object o1, Object o2) {
    // nulls are "greater" than non-nulls
    if (o1 == null && o2 != null) return 1;
    // non-nulls are "smaller" than nulls
    if (o1 != null && o2 == null) return -1;
    // in all other comparisons, we don't care
    return 0;
  }
});
Run Code Online (Sandbox Code Playgroud)

或者使用Java 8:

Arrays.sort(theHeap, (o1, o2) -> (o1 == null && o2 != null) ?  1
                               : (o1 != null && o2 == null) ? -1
                               :                               0);
Run Code Online (Sandbox Code Playgroud)

如果你的类路径上有Apache Commons Collections,你可以用更少的代码编写它:

Arrays.sort(theHeap, new NullComparator());
Run Code Online (Sandbox Code Playgroud)

正如Ted所提到的,这可以执行O(n log n)并创建一个用于排序的数组克隆......因此它不是最快的解决方案......