1

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?

For example: [1, 2, 6, null, 9, 5, 4, null, 2, 3] To: [1, 2, 2, 3, 4, 5, 6, 9, null, null]

0

2 Answers 2

1

It can be done with 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) {
    // ...
}

I converted the Comparable comparison criteria into a Comparator using Comparator.naturalOrder.

Sign up to request clarification or add additional context in comments.

Comments

0

One option is to write a compareTo function that handles 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) {

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.