Home > Java > javaTutorial > How to Sort an Integer Array in Java from Lowest to Highest?

How to Sort an Integer Array in Java from Lowest to Highest?

DDD
Release: 2024-12-13 07:02:10
Original
754 people have browsed it

How to Sort an Integer Array in Java from Lowest to Highest?

Sorting an Array in Java

Question:

How can I sort an array of 10 integers in order from lowest to highest value in a Java program?

Solution:

import java.util.Arrays;

public static void main(String args[]) {
    int[] array = new int[10];

    array[0] = ((int) (Math.random() * 100 + 1));
    array[1] = ((int) (Math.random() * 100 + 1));
    array[2] = ((int) (Math.random() * 100 + 1));
    array[3] = ((int) (Math.random() * 100 + 1));
    array[4] = ((int) (Math.random() * 100 + 1));
    array[5] = ((int) (Math.random() * 100 + 1));
    array[6] = ((int) (Math.random() * 100 + 1));
    array[7] = ((int) (Math.random() * 100 + 1));
    array[8] = ((int) (Math.random() * 100 + 1));
    array[9] = ((int) (Math.random() * 100 + 1));

    // Sort the array in place from lowest to highest value
    Arrays.sort(array);

    // Print the sorted array
    System.out.println(Arrays.toString(array));
}
Copy after login

To sort the array in Java, we can use the Arrays.sort() method. This method takes an array as input and sorts it in ascending order, using the natural ordering of its elements. In the provided code, the line Arrays.sort(array); is added before printing the sorted array.

After sorting, the elements in the array variable will be ordered from lowest to highest value. The Arrays.toString() method is then used to convert the sorted array into a string representation for printing.

The above is the detailed content of How to Sort an Integer Array in Java from Lowest to Highest?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template