How to use Java sorting algorithms?

In Java, sorting algorithms can be utilized by invoking the sort method from the Arrays class or Collections class. Both of these methods in the classes utilize the quicksort algorithm for implementation.

Example of sorting method using Arrays class:

import java.util.Arrays;

public class SortExample {
    public static void main(String[] args) {
        int[] array = {5, 3, 2, 4, 1};
        
        Arrays.sort(array);
        
        System.out.println(Arrays.toString(array));
    }
}

Example of using the sorting method of the Collections class:

import java.util.ArrayList;
import java.util.Collections;

public class SortExample {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(5);
        list.add(3);
        list.add(2);
        list.add(4);
        list.add(1);
        
        Collections.sort(list);
        
        System.out.println(list);
    }
}

In the examples above, an array or ArrayList object is first created, then sorted using the sort method, and finally the sorted results are printed.

It is important to note that the sort method by default sorts elements in natural order. If a custom sorting rule is needed, you can implement a custom comparator using the Comparator interface.

bannerAds