簡體   English   中英

如何使用插入排序對包含 null 元素的數組進行排序

[英]How to sort an array with null elements using insertion sort

如果我使用如下所示的插入排序並且有一個數組,其中一些元素是整數,然后是 null - 我將如何 go 關於使用 null 對數組進行排序?

例如: [1, 2, 6, null, 9, 5, 4, null, 2, 3] 至: [1, 2, 2, 3, 4, 5, 6, 9, Z309A625786640C1]

public static <T extends Comparable<? super T>> void
            insertionSort(T[] array) {
        for (int sorted = 0; // only the first element is sorted
             sorted < array.length - 1;
             sorted++) { 

            T newElement = array[sorted + 1]; 

            int compareTo = sorted; 
            while (compareTo >= 0 && 
                    newElement.compareTo(array[compareTo]) < 0) {

                
                array[compareTo + 1] = array[compareTo];
                compareTo--;
            }
            
            array[compareTo + 1] = newElement;
        }
    }

一種選擇是編寫一個compareTo function 來處理null

public static <T extends Comparable<? super T>> int compareTo(T a, T b)
{
    if (a == null && b == null) return 0;
    if (a == null) return 1;
    if (b == null) return -1;
    return a.compareTo(b);
}

然后讓插入排序使用:

while (compareTo >= 0 && compareTo(newElement, array[compareTo]) < 0) {

可以使用Comparator.nullsLast來完成:

public static <T extends Comparable<? super T>> void insertionSort(T[] array) {
    Comparator<T> comparator = Comparator.nullsLast(Comparator.naturalOrder());
    // ...
    int compareTo = sorted;
    while (compareTo >= 0 && comparator.compare(newElement, array[compareTo]) < 0) {
    // ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM