How to Sort an Array in Java

Instructions to Sort an Array in Java

The arranging is a method for orchestrating components of a rundown or cluster in a specific request. The request might be in rising or dropping request. The mathematical and lexicographical (sequential) request is a broadly utilized request.

In this segment, we will figure out how to sort cluster in Java in rising and sliding request utilizing the sort() technique and without utilizing the sort() strategy. Alongside this, we will likewise figure out how to sort subarray in Java.

A cluster class is a class containing static strategies that are utilized with exhibits to look, sort, analyze, embedding components, or returning a string portrayal of a cluster. in a cluster. So let us determine the capacities first and later onwards we will examine something similar. They are as per the following been available in java.util.Arrays class.

Here we will talk about out various plots utilizing the sort() technique for the Arrays class.

This Tutorial will Explain Various Methods to Sort An Array in Java in Ascending, Descending and Alphabetical Order with the assistance of Simple Examples:

Arranging organizes information in a particular request. PC information comprises of records comprised of at least one fields. To utilize information productively and perform different tasks like looking, getting to, and so on it is prudent that this information is organized in some particular request.

For Example, assuming that there are various records of understudy information, then, at that point, we could orchestrate this information relying upon the understudy id or understudy name. This is named as arranging. Henceforth arranging is crucial for utilize the information all the more proficiently and without any problem.
Arrays.sort() strategy comprises of two varieties one in which we don’t pass any contentions where it sort down the total exhibit be it whole number cluster or character cluster yet assuming that we should sort a particular part utilizing this technique for Arrays class then we over-burden it and pass the beginning and last list to the cluster.

Boundaries: It accepts three boundaries as can be seen from the grammar which is as per the following:

  • The cluster to be arranged
  • The record of the primary component, comprehensive, to be arranged (Referred to as from_index)
  • The file of the last component, select, to be arranged (Referred to as last_index)
  • Bring Type back: It doesn’t return any worth.

Utilizing the sort() Method

In Java, Arrays is the class characterized in the java.util bundle that gives sort() technique to sort an exhibit in rising request. It utilizes Dual-Pivot Quicksort calculation for arranging. Its intricacy is O(n log(n)). It is a static technique that parses an exhibit as a boundary and brings nothing back. We can conjure it straightforwardly utilizing the class name. It acknowledges a variety of type int, float, twofold, long, roast, byte.

Example 1:

// Java Program to Sort Array of Integers
// by Default Sorts in an Ascending Order
// using Arrays.sort() Method
 
// Importing Arrays class from the utility class
import java.util.Arrays;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input array
        int[] arr = { 13, 7, 6, 45, 21, 9, 101, 102 };
 
        // Applying sort() method over to above array
        // by passing the array as an argument
        Arrays.sort(arr);
 
        // Printing the array after sorting
        System.out.println("Modified arr[] : %s",
                           Arrays.toString(arr));
    }
}

Output: 

Modified arr[] : [6, 7, 9, 13, 21, 45, 101, 102]

Example 2:

// Java program to Sort a Subarray in Array
// Using Arrays.sort() method
 
// Importing Arrays class from java.util package
import java.util.Arrays;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input array
        // It contains 8 elements as follows
        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 the updated array which is
        // sorted after 2 index inclusive till 5th index
        System.out.println("Modified arr[] : %s",
                           Arrays.toString(arr));
    }
}

Output: 

Modified arr[] : [13, 6, 7, 21, 45, 9, 2, 100]

Example 3:

// Java program to Sort a Subarray in Descending order
// Using Arrays.sort()
 
// Importing Collections class and arrays classes
// from java.util package
import java.util.Arrays;
import java.util.Collections;
 
// Main class
public class GFG {
   
    // Main driver method
    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 using
        // reverseOrder() method of Collections class
        // in Array.sort() as an argument to it
        Arrays.sort(arr, Collections.reverseOrder());
 
        // Printing the array as generated above
        System.out.println("Modified arr[] : %s",
                           Arrays.toString(arr));
    }
}

Output: 

Modified arr[] : [100, 45, 21, 13, 9, 7, 6, 2]

Example 4:

// Java program to sort an array of strings
// in ascending and descending alphabetical order
// Using Arrays.sort()
 
// Importing arrays and Collections class
// from java.util class
import java.util.Arrays;
import java.util.Collections;
 
// Main class
public class GFG {
   
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input string
        String arr[] = { "practice.geeksforgeeks.org",
                         "quiz.geeksforgeeks.org",
                         "code.geeksforgeeks.org" };
 
        // Sorts arr[] in ascending order
        Arrays.sort(arr);
        System.out.println("Modified arr[] : \n%s\n\n",
                           Arrays.toString(arr));
 
        // Sorts arr[] in descending order
        Arrays.sort(arr, Collections.reverseOrder());
 
        // Lastly printing the above array
        System.out.println("Modified arr[] : \n%s\n\n",
                           Arrays.toString(arr));
    }
}

Output: 

Modified arr[] :

Modified arr[] : 
[quiz.geeksforgeeks.org, practice.geeksforgeeks.org, code.geeksforgeeks.org]

Now lastly we will be implementing the sort() method to the fullest because here we will be declaring our own defined criteria with the help of the Comparator interface.

Example 5:

// Java program to demonstrate Working of 
// Comparator interface
 
// Importing required classes
import java.io.*;
import java.lang.*;
import java.util.*;
 
// Class 1
// A class to represent a student.
class Student {
    int rollno;
    String name, address;
 
    // Constructor
    public Student(int rollno, String name, String address)
    {
        // This keyword refers to current object itself
        this.rollno = rollno;
        this.name = name;
        this.address = address;
    }
 
    // Used to print student details in main()
    public String toString()
    {
        return this.rollno + " " + this.name + " "
            + this.address;
    }
}
 
// Class 2
// Helper class extending Compatator interface
class Sortbyroll implements Comparator<Student> {
    // Used for sorting in ascending order of
    // roll number
    public int compare(Student a, Student b)
    {
        return a.rollno - b.rollno;
    }
}
 
// Class 3
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        Student[] arr
            = { new Student(111, "bbbb", "london"),
                new Student(131, "aaaa", "nyc"),
                new Student(121, "cccc", "jaipur") };
 
        System.out.println("Unsorted");
 
        for (int i = 0; i < arr.length; i++)
            System.out.println(arr[i]);
 
        // Sorting on basic as per class 1 created
        // (user-defined)
        Arrays.sort(arr, new Sortbyroll());
 
        System.out.println("\nSorted by rollno");
 
        for (int i = 0; i < arr.length; i++)
            System.out.println(arr[i]);
    }
}

Output: 

Unsorted
111 bbbb london
131 aaaa nyc
121 cccc jaipur

Sorted by rollno
111 bbbb london
121 cccc jaipur
131 aaaa nyc

Also Read:

Leave a Reply

Your email address will not be published.