Method Arrays.sort()

Author: Tatyana Milkina

Sorting arrays is a common task in Java application development. The Arrays.sort() method from the java.util package allows you to sort the elements of an array in ascending order quickly and efficiently.

Here’s a basic example showing how to sort an array of integers:

import java.util.Arrays;

public class ArraysSortExample1 {
    public static void main(String[] args) {
        int[] array = new int[]{3, 1, 5, 6, 8};
        Arrays.sort(array);
        System.out.println(Arrays.toString(array));
    }
}

Output:

[1, 3, 5, 6, 8]

The Arrays.sort() method uses a Dual-Pivot Quicksort algorithm for primitive types, which is optimized for performance and handles most input efficiently. For object arrays, such as String[], it uses a modified mergesort algorithm that is stable.

You can also sort arrays of other data types such as double[], char[], or arrays of objects using custom comparators with Arrays.sort(). This makes it a powerful and flexible tool for ordering data in Java.

Sorting is essential in many real-world scenarios, such as displaying sorted lists, performing efficient searches, or preparing data for binary search.

Курс 'Java для начинающих' на Udemy Курс 'Java для начинающих' на Udemy
Read also:
Comments