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)); }
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!