Ask Your Question
2

How can we arrange an array of objects in ascending order, and move any null values to the end of the array?

asked 2021-09-07 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-11-08 22:00:00 +0000

lalupa gravatar image

One possible way to achieve this is:

  1. Remove all null elements from the array and store them in a separate array. This can be done using a loop that iterates over the original array and checks if each element is null. If so, remove it and add it to the new array.

  2. Sort the remaining elements in ascending order. This can be done using the built-in Arrays.sort() method.

  3. Append the null array to the sorted array to create a new array. This can be done using the Arrays.copyOf() method to create a new array with the combined length of both arrays, and then copying the elements of both arrays into the new array using a loop.

Here's some sample code that implements this approach:

// Example array of objects
Object[] array = { null, "b", "a", null, "c" };

// Remove null elements
Object[] nullArray = new Object[array.length];
int nullIndex = 0;
for (int i = 0; i < array.length; i++) {
    if (array[i] == null) {
        nullArray[nullIndex++] = array[i];
        array[i] = null; // Set original element to null
    }
}
Object[] sortedArray = Arrays.copyOf(array, array.length - nullIndex);

// Sort non-null elements
Arrays.sort(sortedArray);

// Combine sorted and null arrays
Object[] newArray = Arrays.copyOf(sortedArray, sortedArray.length + nullIndex);
for (int i = 0; i < nullIndex; i++) {
    newArray[sortedArray.length + i] = nullArray[i];
}

After executing this code, the newArray variable should contain the sorted array with null elements at the end.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-09-07 11:00:00 +0000

Seen: 8 times

Last updated: Nov 08 '22