Home >Java >javaTutorial >How Can I Sort an Array of Integers in Java?

How Can I Sort an Array of Integers in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-12-10 10:04:10598browse

How Can I Sort an Array of Integers in Java?

Sorting an Array in Java

Sorting an array involves organizing its elements in a specific order, typically from lowest to highest or vice versa. In your case, you aim to sort an array of 10 random integers from lowest to highest.

To achieve this, Java provides the Arrays.sort() method. This method takes an array as an argument and modifies it in-place, arranging its elements in ascending order (from lowest to highest).

In your code, you can incorporate Arrays.sort() as follows:

int[] array = new int[10];

// Populate the array with random values
...

// Sort the array
Arrays.sort(array);

// Print the sorted array
System.out.println(array[0] + " " + array[1] + " " + array[2] + " " + array[3]
        + " " + array[4] + " " + array[5] + " " + array[6] + " " + array[7] + " "
        + array[8] + " " + array[9]);

The Arrays.sort() method effectively sorts your array in ascending order. As a result, when you print the array, its elements will be displayed in the desired order.

The above is the detailed content of How Can I Sort an Array of Integers in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn