Java
Home Education How to Sort an Array in Java – A Complete Guide

How to Sort an Array in Java – A Complete Guide

by Williami

Sorting arrays is one of the most common tasks in programming, and Java provides several methods—both built-in and manual—to handle array sorting efficiently, whether you’re sorting numbers in ascending order or arranging strings alphabetically. Understanding how sorting works is a key part of Java development.

This tutorial covers various techniques to sort arrays in Java, including ascending and descending order, using built-in utilities, loops, and user-defined methods. By the end, you’ll know how to apply the right sorting method for different data types and use cases.

What Is Sorting?

Sorting is the process of arranging elements in a specific sequence, typically ascending (smallest to largest) or descending (largest to smallest). For example, consider organizing playing cards from the lowest to the highest number.

In programming, sorting helps:

Java
  • Speed up searching
  • Make data easier to analyze
  • Prepare datasets for algorithms like binary search

Sorting Arrays in Ascending Order

Ascending order arranges the elements from lowest to highest. Java provides several ways to achieve this.

Read More: How Valuable Are Certificates from Coursera, edX, and Udemy

Using Arrays.sort() Method

The simplest way to sort an array in ascending order is by using Java’s built-in Arrays.sort() method from the java.util package. Internally, it uses the Dual-Pivot Quicksort algorithm for primitives, offering an average time complexity of O(n log n).

Syntax:

public static void sort(int[] array)

Example

import java.util.Arrays;

class Main {
    public static void main(String[] args) {
        int[] array = {33, 2, 34, 534, 1, 93};
        Arrays.sort(array);
        for (int i : array) {
            System.out.print(i + " ");
        }
    }
}

Without Built-in Method: Using for Loop

You can manually sort arrays using nested loops, typically through a basic bubble sort or selection sort approach.

Java

Example:

public class SortingExample {
    public static void main(String[] args) {
        int[] arr = {435, 93, 34, 53, 12, 334, 53, 34, 23, 34};
        for (int i = 0; i < arr.length; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] > arr[j]) {
                    int temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
            System.out.print(arr[i] + " ");
        }
    }
}

Using a User-Defined Method

For better modularity, you can implement your own sorting logic in a reusable method.

Example:

javaCopyEdit
public class Main {
    public static void main(String[] args) {
        int[] array = {34, 55, 99, 23, 5, 34, 21, 1};
        sortArray(array, array.length);
        for (int value : array) {
            System.out.print(value + " ");
        }
    }

    private static void sortArray(int[] array, int n) {
        for (int i = 1; i < n; i++) {
            int a = array[i];
            int j = i;
            while (j > 0 && array[j - 1] > a) {
                array[j] = array[j - 1];
                j--;
            }
            array[j] = a;
        }
    }
}

Sorting Arrays in Descending Order

Descending order arranges elements from highest to lowest. Java allows this in both built-in and custom ways.

Using Collections.reverseOrder()

To sort in descending order, use Arrays.sort() with Collections.reverseOrder()—only works with object types like Integer, not primitives.

Example:

javaCopyEdit
import java.util.Arrays;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        Integer[] array = {3, 4, 1, 5, 9, 3, 4};
        Arrays.sort(array, Collections.reverseOrder());
        System.out.println(Arrays.toString(array));
    }
}

Sorting Strings in Descending Order

import java.util.Arrays;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        String[] strArray = {"Harry", "Potter", "Voldemort", "Computer", "Singhaniya", "Watermelon"};
        Arrays.sort(strArray, Collections.reverseOrder());
        System.out.println(Arrays.toString(strArray));
    }
}

Output:
[Watermelon, Voldemort, Singhaniya, Potter, Harry, Computer]

Without Built-in Methods: Manual Loop

Manual descending sort using nested loops:

public class Main {
    public static void main(String[] args) {
        int[] array = {12, 5, 9, 1, 4, 2, 5, 9, 34, 53};
        for (int i = 0; i < array.length; i++) {
            for (int j = i + 1; j < array.length; j++) {
                if (array[i] < array[j]) {
                    int temp = array[i];
                    array[i] = array[j];
                    array[j] = temp;
                }
            }
        }
        for (int i : array) {
            System.out.print(i + " ");
        }
    }
}

Output:
53 34 12 9 9 5 5 4 2 1

User-Defined Method for Descending Order

public class Main {
    public static void main(String[] args) {
        int[] array = {33, 4, 5, 3, 31, 2, 3};
        sortDescending(array);
        for (int value : array) {
            System.out.print(value + " ");
        }
    }

    public static void sortDescending(int[] a) {
        int temp;
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = i + 1; j < a.length; j++) {
                if (a[i] < a[j]) {
                    temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }
            }
        }
    }
}

Output:
33 31 5 4 3 3 2

Sorting Subarrays in Java

Java also supports sorting only a portion of an array—known as a subarray. Use the overloaded Arrays.sort() method.

Java

Syntax:

public static void sort(int[] array, int fromIndex, int toIndex)
  • fromIndex is inclusive
  • toIndex is exclusive
import java.util.Arrays; public class Main { public static void main(String[] args) { int[] a = {33, 23, 1, 53, 2, 4, 9, 1}; Arrays.sort(a, 2, 7); // sorts elements from index 2 to 6 System.out.print(“Sorted Array = “); for (int value : a) { System.out.print(value + ” “); } } }

Output:

Sorted Array = 33 23 1 2 4 9 53 1

FAQs

What built-in methods can I use to sort arrays in Java?

Java offers Arrays.sort() for primitive types and objects. For descending order, use Collections.reverseOrder() with object arrays like Integer[].

Can I sort an array of custom objects?

Yes, by implementing the Comparable interface in the class or passing a custom Comparator to Arrays.sort().

Is it possible to sort arrays containing null values?

Sorting arrays with null values will throw a NullPointerException. Handle or remove nulls before sorting.

Can I sort a subarray in Java?

Yes. Use Arrays.sort(array, fromIndex, toIndex) to sort only a selected range within the array.

Can boolean arrays be sorted?

Not directly using Arrays.sort(). You must convert boolean values to integers (0/1), sort them, and convert them back.

Conclusion

Sorting arrays is an essential skill in Java programming. Whether you’re working with numbers, strings, or custom objects, Java provides versatile ways to sort arrays efficiently. From simple built-in methods like Arrays.sort() to custom implementations using loops, understanding these approaches allows you to write clean, efficient, and adaptable code. Mastering array sorting will boost both your logic and real-world problem-solving capabilities in Java development.

You may also like

Leave a Comment