简体   繁体   English

如何使用插入排序对包含 null 元素的数组进行排序

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

If I am using insertion sort as shown below and have an array with some elements that are integers and then some that are null - How would I go about sorting that array with the null elements at the end using insertion sort?如果我使用如下所示的插入排序并且有一个数组,其中一些元素是整数,然后是 null - 我将如何 go 关于使用 null 对数组进行排序?

For example: [1, 2, 6, null, 9, 5, 4, null, 2, 3] To: [1, 2, 2, 3, 4, 5, 6, 9, null, 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;
        }
    }

One option is to write a compareTo function that handles null :一种选择是编写一个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);
}

Then have the insertion sort use that:然后让插入排序使用:

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

It can be done with Comparator.nullsLast :可以使用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