Sorting in Java

03 Oct, 2021
Whenever we do hear sorting algorithms come into play such as selection sort, bubble sort, insertion sort, radix sort, bucket sort, etc but if we look closer here we are not asked to use any kind of algorithms. It is as simple sorting with the help of linear and non-linear data structures present within java. So there is sorting done with the help of brute force in java with the help of loops and there are two in-built methods to sort in Java. 
Ways of sorting in Java
Using loopsUsing sort() method of Arrays classUsing sort method of Collections classSorting on a subarray
Using loops
Using sort() method of Arrays class
Using sort method of Collections class
Sorting on a subarray
Let us discuss all four of them and propose a code for each one of them.
Way 1: Using loops
Java
// Java Program to sort an elements// by bringing Arrays into play // Main classclass GFG {     // Main driver method    public static void main(String[] args)    {         // Custom input array        int arr[] = { 4, 3, 2, 1 };         // Outer loop        for (int i = 0; i < arr.length; i++) {             // Inner nested loop pointing 1 index ahead            for (int j = i + 1; j < arr.length; j++) {                 // Checking elements                int temp = 0;                if (arr[j] < arr[i]) {                     // Swapping                    temp = arr[i];                    arr[i] = arr[j];                    arr[j] = temp;                }            }             // Printing sorted array elements            System.out.print(arr[i] + " ");        }    }}
1 2 3 4 
Way 2: Using sort() method of Arrays class  
Arrays.Sort() works for arrays which can be of primitive data type also which in turn by default sorts in ascending order.
Example 1
JAVA
// Java program to demonstrate working of// sort() method of Arrays class // Importing Arrays class from java.util packageimport java.util.Arrays; // Main classpublic class GFG {     // Main driver method    public static void main(String[] args)    {        // Custom input array        int[] arr = { 13, 7, 6, 45, 21, 9, 101, 102 };         // Calling the sort() method present        // inside Arrays class        Arrays.sort(arr);         // Printing and display sorted array        System.out.printf("Modified arr[] : %s",                          Arrays.toString(arr));    }}
Modified arr[] : [6, 7, 9, 13, 21, 45, 101, 102]
Example 2
JAVA
// A sample Java program to sort an array// in descending order using Arrays.sort().import java.util.Arrays;import java.util.Collections; public class GFG {    public static void main(String[] args)    {        // Note that we have Integer here instead of        // int[] as Collections.reverseOrder doesn't        // work for primitive types.        Integer[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 };         // Sorts arr[] in descending order        Arrays.sort(arr, Collections.reverseOrder());         System.out.printf("Modified arr[] : %s",                          Arrays.toString(arr));    }}
Modified arr[] : [100, 45, 21, 13, 9, 7, 6, 2]
Way 3: Using sort() method of Collections class 
Collections.sort() works for objects Collections like ArrayList and LinkedList.
Example
JAVA
// Java program to demonstrate working of Collections.sort()import java.util.*; public class GFG {    public static void main(String[] args)    {        // Create a list of strings        ArrayList<String> al = new ArrayList<String>();        al.add("Geeks For Geeks");        al.add("Friends");        al.add("Dear");        al.add("Is");        al.add("Superb");         /* Collections.sort method is sorting the        elements of ArrayList in ascending order. */        Collections.sort(al);         // Let us print the sorted list        System.out.println("List after the use of"                           + " Collection.sort() :\n" + al);    }}
List after the use of Collection.sort() :
[Dear, Friends, Geeks For Geeks, Is, Superb]
Example 2
JAVA
// Java program to demonstrate working of Collections.sort()// to descending order.import java.util.*; public class GFG {    public static void main(String[] args)    {        // Create a list of strings        ArrayList<String> al = new ArrayList<String>();        al.add("Geeks For Geeks");        al.add("Friends");        al.add("Dear");        al.add("Is");        al.add("Superb");         /* Collections.sort method is sorting the        elements of ArrayList in ascending order. */        Collections.sort(al, Collections.reverseOrder());         // Let us print the sorted list        System.out.println("List after the use of"                           + " Collection.sort() :\n" + al);    }}
List after the use of Collection.sort() :
[Superb, Is, Geeks For Geeks, Friends, Dear]
Way 4: Sorting only a subarray
JAVA
// Java program to sort a subarray// using Arrays.sort() // Importing Arrays class from java.util packageimport java.util.Arrays; // Main classpublic class GFG {     // Main drive method    public static void main(String[] args)    {        // Custom input array        int[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 };         // Sort subarray from index 1 to 4, i.e.,        // only sort subarray {7, 6, 45, 21} and        // keep other elements as it is.        Arrays.sort(arr, 1, 5);         // Printing sorted array        System.out.printf("Modified arr[] : %s",                          Arrays.toString(arr));    }}
Modified arr[] : [13, 6, 7, 21, 45, 9, 2, 100]
Note:
Which sorting algorithm does Java use in sort()? Previously, Java’s Arrays.sort method used Quicksort for arrays of primitives and Merge sort for arrays of objects. In the latest versions of Java, Arrays.sort method and Collection.sort() uses Timsort.
Which order of sorting is done by default? It by default sorts in ascending order.
How to sort array or list in descending order? It can be done with the help of Collections.reverseOrder().
How to write my own sorting function in Java? Please see Java programs for Quick Sort, Merge Sort, Insertion Sort, Selection Sort, Heap Sort, Bubble Sort
samyanib
solankimayank
Java-Arrays
Java-Collections
Java
Java Programs
Sorting
Sorting
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
How to add an element to an Array in Java?
Queue Interface In Java
List Interface in Java with Examples
PriorityQueue in Java
Initializing a List in Java
Java Programming Examples
Convert a String to Character Array in Java
Convert Double to Integer in Java
Implementing a Linked List in Java using Class