Code Logo

Sort Array with Arrays.sort()

Published at25 Jul 2026
Collections Framework Easy 0 views
Like0

Write a Java function that takes an array of integers and returns a new sorted array using Arrays.sort(). The Arrays utility class provides static methods for common array operations including sorting, searching, and copying.java.util.Arrays.sort() sorts the specified array into ascending numerical order using a highly optimized Dual-Pivot Quicksort algorithm for primitives (int[], double[], etc.) and TimSort for object arrays (Integer[], String[], etc.). The algorithm has O(n log n) average time complexity and is significantly faster than simple sorting algorithms like bubble sort.

The Arrays class is part of the java.util package and provides many useful array utilities: sort() for sorting, binarySearch() for searching, copyOf() for copying, fill() for filling with values, equals() and deepEquals() for comparison, and toString() for string representation. These methods make array manipulation in Java convenient and efficient.

Time complexity is O(n log n) where n is the array length. Space complexity is O(log n) for the recursive sorting algorithm (in-place for primitives). The sort method modifies the original array, so create a copy if the original needs preservation.

Edge cases include empty arrays (nothing to sort), single-element arrays (already sorted), arrays with duplicate values, negative numbers, and large arrays with many elements.

Example Input & Output

Example 1
Input
[-1,3,0,-2]
Output
[-2,-1,0,3]
Explanation

With negatives

Example 2
Input
[]
Output
[]
Explanation

Empty array

Example 3
Input
[10]
Output
[10]
Explanation

Single element

Example 4
Input
[3,1,2]
Output
[1,2,3]
Explanation

Simple sort

Example 5
Input
[5,5,5]
Output
[5,5,5]
Explanation

All same values

Algorithm Flow

Recommendation Algorithm Flow for Sort Array with Arrays.sort()
Recommendation Algorithm Flow for Sort Array with Arrays.sort()

Solution Approach

import java.util.Arrays;

class Solution {
    public int[] solution(int[] nums) {
        int[] sorted = nums.clone();
        Arrays.sort(sorted);
        return sorted;
    }
}

Best Answers

java - Approach 1
import java.util.Arrays;

class Solution {
    public int[] solution(int[] nums) {
        int[] sorted = nums.clone();
        Arrays.sort(sorted);
        return sorted;
    }
}