How to Sort an Array in Java: A Step-by-Step Guide
In this guide, we'll explore how to efficiently sort an array of randomly generated integers in Java. Let's delve into the provided code:
public static void main(String args[]) { int[] array = new int[10]; // Populate the array with random values for (int i = 0; i < array.length; i++) { array[i] = ((int) (Math.random() * 100 + 1)); } // Print the original array for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } System.out.println(); // Sort the array Arrays.sort(array); // Print the sorted array for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } }
Step 1: Populating the Array
An array is initialized with a size of 10, and each element is assigned a random integer between 1 and 100.
Step 2: Sorting the Array
To sort the array, we invoke the Arrays.sort() method. This utility method sorts the entire array in ascending order.
Step 3: Printing the Sorted Array
After sorting the array, it is printed to the screen, displaying the elements in ascending order.
Note: The original array is modified during sorting, so the printed original array will match the sorted version.
The above is the detailed content of How Can I Sort an Array of Random Integers in Java?. For more information, please follow other related articles on the PHP Chinese website!