Java Array Sorting

Introduction

Array sorting is the process of arranging array elements in a specific order, usually ascending (smallest to largest) or descending (largest to smallest).

Imagine an application that stores students’ marks, employee salaries, or product prices. If the values are not organized, finding the highest score or displaying products by price becomes difficult. Sorting solves this problem by arranging the data in a meaningful order.

Java provides a powerful utility class called java.util.Arrays, which includes the sort() method for efficiently sorting arrays. Behind the scenes, Java uses highly optimized sorting algorithms depending on the data type, making Arrays.sort() the preferred approach for most applications.

What is Array Sorting?

Array sorting is the process of arranging the elements of an array in a particular order.

The two most common orders are:

  • Ascending Order – Smallest to Largest
  • Descending Order – Largest to Smallest

Example:

Before sorting:


50 10 40 20 30

After sorting (Ascending):


10 20 30 40 50

After sorting (Descending):


50 40 30 20 10

Why Do We Need Array Sorting?

Sorting is useful because it:

  • Makes searching faster.
  • Improves data readability.
  • Simplifies reporting.
  • Helps remove duplicates.
  • Supports binary search.
  • Organizes large datasets efficiently.

Sorting is commonly used in:

  • Student management systems
  • Banking applications
  • E-commerce websites
  • Payroll systems
  • Data analytics
  • Inventory management

Sorting Using Arrays.sort()

The easiest way to sort an array in Java is by using the Arrays.sort() method from the java.util.Arrays class.

Syntax


Arrays.sort(arrayName);

Sorting an Integer Array

Example:


impot java.util.Arrays;
public class Main {
    public static void main(String[] args) {
        int[] numbers = {50, 20, 10, 40, 30};
        Arrays.sort(numbers);
        System.out.println(Arrays.toString(numbers));
    }
}

Output

[10, 20, 30, 40, 50]

The array is sorted in ascending order.

Sorting a String Array

The Arrays.sort() method also works with strings.


import java.util.Arrays;
public class Main {
    public static void main(String[] args) {
        String[] fruits = {
            "Mango",
            "Apple",
            "Banana"
        };
        Arrays.sort(fruits);
        System.out.println(Arrays.toString(fruits));
    }
}

Output

[Apple, Banana, Mango]

Strings are sorted alphabetically based on their Unicode values.

Sorting in Descending Order

Primitive arrays cannot be directly sorted in descending order using Arrays.sort(). One common approach is to sort in ascending order first and then traverse the array in reverse.

Example:


import java.util.Arrays;
public class Main {
    public static void main(String[] args) 
        int[] numbers = {50, 20, 10, 40, 30};
        Arrays.sort(numbers);
        for (int i = numbers.length - 1; i >= 0; i--) {
            System.out.print(numbers[i] + " ");
        }
    }
}

Output

50 40 30 20 10

For object arrays such as Integer[], you can also use a reverse-order comparator.


import java.util.Arrays;
import java.util.Collections;
Integer[] numbers = {50, 20, 10, 40, 30};
Arrays.sort(numbers, Collections.reverseOrder());
System.out.println(Arrays.toString(numbers));
50 40 30 20 10

Bubble Sort

Bubble Sort repeatedly compares adjacent elements and swaps them if they are in the wrong order.

Example:


public class Main {
    public static void main(String[] args) {
        int[] numbers = {5, 2, 4, 1, 3};
        for (int i = 0; i < numbers.length - 1; i++) {
            for (int j = 0; j  numbers[j + 1]) {
                    int temp = numbers[j];
                    numbers[j] = numbers[j + 1];
                    numbers[j + 1] = temp;
                }
            }
        }
        for (int number : numbers) {
            System.out.print(number + " ");
        }
    }
}

Output

1 2 3 4 5

Bubble Sort is simple to understand but inefficient for large datasets.

Selection Sort

Selection Sort repeatedly finds the smallest element and places it at the correct position.

Example:


int[] numbers = {64, 25, 12, 22, 11};
for (int i = 0; i < numbers.length - 1; i++) {
    int inIndex = i;
    for (int j = i + 1; j < numbers.length; j++) {
        if (numbers[j] < numbers[minIndex]) {
            minIndex = j;
        }
    }
    int temp = numbers[minIndex];
    numbers[minIndex] = numbers[i];
    numbers[i] = temp;
}

Selection Sort performs fewer swaps than Bubble Sort but still has quadratic time complexity.

Insertion Sort

Insertion Sort builds the sorted portion of the array one element at a time.

Example:


int[] numbers = {12, 11, 13, 5, 6};
for (int i = 1; i = 0 && numbers[j] > key) {
        numbers[j + 1] = numbers[j];
        j--;
    }
    numbers[j + 1] = key;
}

Insertion Sort performs well for small or nearly sorted arrays.

Sorting Custom Objects

You can sort custom objects by implementing the Comparable interface or by using a Comparator.

Example:


import java.util.Arrays;
class Student implements Comparable {
    String name;
    int marks;
    Student(String name, int marks) {
        this.name = name;
        this.marks = marks;
    }
    @Override
    public int compareTo(Student other) {
        return Integer.compare(this.marks, other.marks);
}
}
public class Main {
    public static void main(String[] args) {
        Student[] students = {
            new Student("Rahul", 85),
            new Student("Amit", 92),
            new Student("Neha", 78)
        };
        Arrays.sort(students);
        for (Student student : students) {
            System.out.println(student.name + " - " + student.marks);
        }
    }
}

Output

Neha – 78
Rahul – 85
Amit – 92

Time Complexity of Common Sorting Algorithms

Algorithm Best Case Average Case Worst Case
Bubble Sort O(n) O(n²) O(n²)
Selection Sort O(n²) O(n²) O(n²)
Insertion Sort O(n) O(n²) O(n²)
Arrays.sort() (Primitives) O(n log n) O(n log n) O(n log n)

For most real-world applications, Arrays.sort() is the preferred choice due to its optimized implementation.

Real-Life Example

Consider an e-commerce application that needs to display product prices from lowest to highest.


import java.util.Arrays;
public class Main {
    public static void main(String[] args) {
        double[] prices = {499.99, 199.99, 299.99, 99.99};
        Arrays.sort(prices);
        System.out.println(Arrays.toString(prices));
    }
}

Output

[99.99, 199.99, 299.99, 499.99]

Sorting allows users to easily compare products by price.

Advantages of Array Sorting

Array sorting provides several benefits:

  • Organizes data efficiently.
  • Improves search performance.
  • Simplifies reporting and analysis.
  • Makes data easier to read.
  • Supports binary search.
  • Enhances user experience in applications.
  • Reduces the complexity of many algorithms.

Best Practices

📖
Best Practices:
  • Prefer Arrays.sort() for production applications.
  • Use Collections.reverseOrder() for descending sorting of object arrays.
  • Choose the appropriate algorithm based on data size.
  • Avoid implementing manual sorting unless required for learning or interviews.
  • Use Comparator or Comparable when sorting custom objects.
  • Keep sorting logic separate from business logic.

Conclusion

Java Array Sorting is a fundamental operation that organizes data into a meaningful order, making searching, reporting, and processing more efficient. Java simplifies sorting through the Arrays.sort() method, which provides a highly optimized and reliable solution for both primitive and object arrays.

Related Java Tutorials