how to sort an array in java

1 minute ago 1
how to sort an array in java

To sort an array in Java, the simplest and most common way is to use the built-in method Arrays.sort() from the java.util.Arrays class. This method sorts the array in ascending order. Here is a basic example:

java

import java.util.Arrays;

public class SortArrayExample {
    public static void main(String[] args) {
        int[] numbers = {5, 3, 8, 1, 2};
        Arrays.sort(numbers);  // Sorts the array in ascending order
        for (int num : numbers) {
            System.out.print(num + " ");
        }
    }
}

Output:

1 2 3 5 8

Key points:

  • Arrays.sort() sorts the entire array.
  • For primitive types, it sorts in natural ascending order.
  • For objects implementing Comparable (e.g., String), it sorts according to their compareTo method.
  • You can also sort a subrange by using Arrays.sort(array, startIndex, endIndex).
  • If you want to sort in descending order, you can use a custom Comparator with Arrays.sort for object arrays; primitive arrays require manual handling or wrapping in objects.

Other sorting options include implementing sorting algorithms like bubble sort, selection sort, or using streams for custom ordering, but Arrays.sort() is the most straightforward and efficient way for general use. This method uses optimized algorithms like Dual-Pivot Quicksort for primitives and MergeSort for objects, ensuring good performance for typical use cases.