Java Tutorial

Operators

Flow Control

String

Number and Date

Built-in Classes

Array

Class and Object

Inheritance and Polymorphism

Exception Handling

Collections, Generics and Enumerations

Reflection

Input/Output Stream

Annotation

Java Array Sorting (Ascending And Descending)

In Java, there are several ways to sort arrays. In this tutorial, we will cover two main methods to sort arrays: using the Arrays.sort() method from the java.util.Arrays class and using the Collections.sort() method with a custom comparator.

1. Sorting an array using Arrays.sort()

Arrays.sort() is a static method provided by the java.util.Arrays class to sort arrays. It can sort both primitive and object arrays. For primitive arrays, it uses a dual-pivot Quicksort algorithm, while for object arrays, it uses a modified merge sort algorithm (TimSort).

Example of sorting a primitive array:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] numbers = {5, 1, 8, 3, 7};

        Arrays.sort(numbers);

        System.out.println("Sorted array: " + Arrays.toString(numbers));
    }
}

Example of sorting an object array:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String[] names = {"Alice", "Charlie", "Bob"};

        Arrays.sort(names);

        System.out.println("Sorted array: " + Arrays.toString(names));
    }
}

2. Sorting an array using Collections.sort() and a custom comparator

For more complex sorting requirements or when sorting arrays of custom objects, you can use the Collections.sort() method with a custom comparator. This method is designed to work with List collections, so you'll need to convert the array to a list first.

Example of sorting an array of custom objects:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Person {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
}

public class Main {
    public static void main(String[] args) {
        Person[] peopleArray = {
                new Person("Alice", 30),
                new Person("Bob", 25),
                new Person("Charlie", 35)
        };

        // Convert the array to a list
        List<Person> peopleList = new ArrayList<>(Arrays.asList(peopleArray));

        // Sort the list using a custom comparator
        Collections.sort(peopleList, Comparator.comparingInt(person -> person.age));

        // Convert the sorted list back to an array
        Person[] sortedArray = peopleList.toArray(new Person[0]);

        System.out.println("Sorted array: " + Arrays.toString(sortedArray));
    }
}

In this example, we first convert the Person array to a list, then sort the list using a custom comparator that compares the age of Person objects. Finally, we convert the sorted list back to an array.

In this tutorial, we covered two main methods to sort arrays in Java: using the Arrays.sort() method for primitive and object arrays, and using the Collections.sort() method with a custom comparator for more complex sorting requirements or when dealing with custom objects.

  1. Sorting Arrays in Ascending Order in Java:

    • Sorting an array of integers in ascending order.
    int[] numbers = {4, 2, 7, 1, 9};
    Arrays.sort(numbers);
    
  2. Java Arrays.sort() Method for Ascending Order:

    • Using Arrays.sort() for ascending order.
    String[] names = {"Alice", "Bob", "Charlie"};
    Arrays.sort(names);
    
  3. Comparable and Comparator in Java Array Sorting:

    • Using Comparable and Comparator interfaces for custom object sorting.
    class Person implements Comparable<Person> {
        // Implement compareTo for Comparable
    }
    Arrays.sort(personArray);
    
  4. Sorting Primitive Arrays in Java:

    • Sorting an array of primitive data types.
    int[] primitiveArray = {4, 2, 7, 1, 9};
    Arrays.sort(primitiveArray);
    
  5. Sorting Arrays of Objects in Java:

    • Sorting an array of custom objects.
    class Student implements Comparable<Student> {
        // Implement compareTo for custom objects
    }
    Arrays.sort(studentArray);
    
  6. Arrays.sort() vs Arrays.parallelSort() in Java:

    • Comparing sequential Arrays.sort() and parallel Arrays.parallelSort().
    int[] numbers = {4, 2, 7, 1, 9};
    Arrays.sort(numbers);
    Arrays.parallelSort(numbers);
    
  7. Sorting Multi-Dimensional Arrays in Java:

    • Sorting a two-dimensional array.
    int[][] matrix = {{4, 2, 7}, {1, 9, 3}};
    Arrays.sort(matrix, Comparator.comparingInt(arr -> arr[0]));
    
  8. Sorting Arrays of Custom Objects in Java:

    • Sorting an array of custom objects using Comparator.
    class Person {
        // Implement Comparator for custom object sorting
    }
    Arrays.sort(personArray, new PersonComparator());
    
  9. Sorting Arrays with Lambda Expressions in Java:

    • Using lambda expressions for concise sorting.
    String[] names = {"Alice", "Bob", "Charlie"};
    Arrays.sort(names, (a, b) -> a.compareTo(b));
    
  10. Java Reverse Order Sorting for Arrays:

    • Sorting an array in descending order.
    int[] numbers = {4, 2, 7, 1, 9};
    Arrays.sort(numbers);
    Arrays.sort(numbers, Collections.reverseOrder());
    
  11. Arrays.sort() for Descending Order in Java:

    • Sorting in descending order using Arrays.sort() and Comparator.
    Integer[] numbers = {4, 2, 7, 1, 9};
    Arrays.sort(numbers, Comparator.reverseOrder());
    
  12. Sorting Arrays using Collections.reverseOrder() in Java:

    • Using Collections.reverseOrder() for reverse sorting.
    String[] names = {"Alice", "Bob", "Charlie"};
    Arrays.sort(names, Collections.reverseOrder());
    
  13. Java Arrays.parallelSort() for Large Arrays:

    • Using Arrays.parallelSort() for improved performance on large arrays.
    int[] largeArray = new int[1_000_000];
    Arrays.parallelSort(largeArray);
    
  14. Stability in Array Sorting Algorithms in Java:

    • The stability of sorting algorithms maintains the relative order of equal elements.
    class Person implements Comparable<Person> {
        // Implement compareTo for stable sorting
    }
    Arrays.sort(personArray);