Java Array sort()
The Arrays.sort()
method in Java is a utility provided by the java.util.Arrays
class to sort arrays of various data types. It is widely used to organize data in ascending order, making it easier to search, analyze, or display.
Usage
The Arrays.sort()
method can be applied to arrays of primitive data types (e.g., int
, char
, double
) and arrays of objects (e.g., String
, Integer
). The method uses a dual-pivot Quicksort algorithm for primitive types and a modified mergesort for object arrays, ensuring efficient sorting.
Syntax
Arrays.sort(array);
Arrays.sort(array, start, end);
array
: The array to be sorted.start
: The index of the first element to sort (optional).end
: The index of the last element to sort (optional).
Examples
Example 1: Sorting an Integer Array
import java.util.Arrays;
public class SortIntegerArray {
public static void main(String[] args) {
int[] numbers = {5, 3, 8, 1, 2};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
}
}
In this example, the Arrays.sort()
method sorts the numbers
array in ascending order. The output will be [1, 2, 3, 5, 8]
.
Example 2: Sorting a String Array
import java.util.Arrays;
public class SortStringArray {
public static void main(String[] args) {
String[] fruits = {"Banana", "Apple", "Cherry", "Date"};
Arrays.sort(fruits);
System.out.println(Arrays.toString(fruits));
}
}
Here, the Arrays.sort()
method sorts the fruits
array alphabetically. The output will be [Apple, Banana, Cherry, Date]
.
Example 3: Sorting a Subarray
import java.util.Arrays;
public class SortSubarray {
public static void main(String[] args) {
int[] numbers = {10, 5, 3, 8, 6, 2};
Arrays.sort(numbers, 1, 4);
System.out.println(Arrays.toString(numbers));
}
}
This example demonstrates sorting a subarray. The Arrays.sort(numbers, 1, 4)
method sorts elements from index 1 to 3. The output will be [10, 3, 5, 8, 6, 2]
.
Tips and Best Practices
- Null Check: Ensure the array is not
null
before callingArrays.sort()
to avoidNullPointerException
. - Performance:
Arrays.sort()
is efficient for most applications, but consider the array size and type when performance is critical. - Custom Sorting: For custom sorting, use
Arrays.sort()
with aComparator
for object arrays.Arrays.sort(fruits, (a, b) -> b.compareTo(a)); // Sorts in descending order
- Immutable Arrays: Remember that
Arrays.sort()
modifies the original array. If the original order needs to be preserved, consider copying the array before sorting. - Thread Safety:
Arrays.sort()
is not thread-safe. Synchronize externally if the array is accessed by multiple threads during sorting.