Arrays.sort() in Java: How to Sort an Array - Quiz

Total: 5 questions

1. 

What does the Arrays.sort() method do, and what does it return?

The static Arrays.sort() method from the java.util.Arrays class sorts the elements of an array in ascending order in place. It is declared as void and returns nothing — it modifies the array you pass in. If you still need the original element order, make a copy before sorting: int[] copy = Arrays.copyOf(array, array.length);

2. 

How do you sort an int[] array in descending order in Java?

You cannot sort an int[] in descending order directly: the Comparator overload works only with object arrays. There are three options. 1) Use Integer[] with Arrays.sort(array, Comparator.reverseOrder()). 2) Sort the int[] in ascending order and reverse it with a loop, swapping elements from both ends toward the middle. 3) Use the Stream API: int[] desc = Arrays.stream(array).boxed().sorted(Comparator.reverseOrder()).mapToInt(Integer::intValue).toArray();

3. 

Which sorting algorithms does Arrays.sort() use under the hood?

For primitive types Arrays.sort() uses Dual-Pivot Quicksort, and for object arrays it uses TimSort, a stable variation of merge sort (since Java 7). Both algorithms run in O(n log n) on average, so there is no reason to hand-write bubble sort in production code.

4. 

What is the difference between Arrays.sort() and Collections.sort()?

Arrays.sort() sorts arrays, including arrays of primitives (which use Dual-Pivot Quicksort). Collections.sort() sorts lists (List) of objects and uses TimSort. Since Java 8, Collections.sort() internally delegates to list.sort(), which also uses TimSort.

5. 

What does Arrays.parallelSort() do, and when should you use it?

Arrays.parallelSort() was introduced in Java 8 and has the same overloads as Arrays.sort(). It splits the array into chunks, sorts them in multiple threads using the Fork/Join pool, and merges the results. On large arrays (hundreds of thousands of elements or more) this pays off on multi-core CPUs; on small arrays it falls back to a regular sequential sort, so you will not see any difference.

Page 1 of 1