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

How Can I Sort an Array of Random Integers in Java?

Susan Sarandon
Release: 2024-12-18 17:44:11
Original
608 people have browsed it

How Can I Sort an Array of Random Integers in Java?

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] + " ");
    }
}
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template