Sorting an Array in Java

If you just need to quickly sort the array, Java sort array operations are super easy with Arrays.sort(). No need to overcomplicate things. Here’s how you can do it:

import java.util.Arrays;

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

        // Populate array with random numbers
        for (int i = 0; i < array.length; i++) {
            array[i] = (int) (Math.random() * 100 + 1);
        }

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

        // Print sorted array
        System.out.println(Arrays.toString(array));
    }
}

:small_blue_diamond: Why this works well?

  • Uses Java’s optimized dual-pivot QuickSort for primitives
  • Clean and readable
  • Just one function call to sort the array

If you just need the sorted array and don’t care about implementation details, this is your best bet.