Home > Java > javaTutorial > Sorting in Java

Sorting in Java

王林
Release: 2024-08-30 15:29:35
Original
486 people have browsed it
  • Sorting in Java is basically arranging a group of elements stored somewhere in a particular order; this order can be both ascending or descending; there come many scenarios in real-time programming where there becomes a necessity to sort the elements as it also makes searching for a particular element easy as the elements can be retrieved easily by an index of arrays directly if sorted. Elements that need to be sorted can be stored either in an array or a collection. The collection is of many types in Java-like Sets, Tree, Map, Heap, List, etc., Though there are different types of Sorting Algorithms that are used to sort the elements in an array-like Bubble Sort Heap Sort, Insertion Sort, Selection Sort, Merge Sort, etc.
  • Programmers use different algorithms to sort the elements according to their specific requirements and the complexity of algorithms. These sorting Algorithms are implemented through the use of various loops and variables to iterate through them. Apart from using the Sorting Algorithms to sort the elements in an array, Java provides the inbuilt function of sorting, which can help with the same, and the programmer does not need to be stuck in big loops and think about complexity. Yes, you heard right, in Java sort() function is used to sort the elements stored either in arrays or collections and that with very less complexity of o(n(logn)). However, the implementation of the method in both is a bit different.

Syntax For Arrays:

Arrays.sort(array_name);
Copy after login

For collections

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Collections.sort(array_name_list);
Copy after login
  • Here array_name and array_name_list is the name of the array or the collection which needs to be sorted.
  • Arrays are the name of classes of Java.
  • The collection is a framework in Java.
  • sort() is the inbuilt sorting function used in Java.

How is Sorting Performed in Java?

Following are the points as follows:

  • Through the use of Sorting Algorithms, sorting can also be performed with algorithms varying from inefficient to efficient, and every algorithm has its own time and space complexity.
  • Sometimes these Algorithms have very high complexity that they can’t be used in real scenarios where there is a need to handle large amounts of data.
  • As mentioned above, in Java inbuilt function, sort() is used to sort all the elements of an Array and collection. According to the official Java DOC, Array.sort uses the quicksort, which is the double pivot and comparatively much faster than the single-pivot Quick Sort.
  • One of the greatest advantages of this is that it provides a complexity of O(n(logn)). It uses the very stable and iterative implementation of the array object of Merge Sort. Java provides a method to sort the array in reverse order too according to the requirement of the programmer to sort either in ascending or descending order. Collections.reverseOrder() method is used to sort the elements in reverse or descending order.
  • Java 8 also provides the facility to sort the arrays parallel using Parallel sorting, which uses the multithreading concept of Java and divides the whole array into parts and merges them after sorting.

Types of Sorting in Java

Below mentioned are some of the ways through which sorting can be performed in Sorting in Java:

1. sort(array_name)

This is used to sort the complete array in ascending. By default, this method sorts the array elements in ascending order.

Code:

import java.util.Arrays;
public class SimpleSort
{
public static void main(String[] args)
{
//Unsorted array of numbers
Integer[] arr = new Integer[] {100, 20, 10, 30, 80, 70, 90, 40, 50, 60};
//Sort function to sort the above array
Arrays.sort(arr);
//Printing the sorted array on console
System.out.println(Arrays.toString(arr));
}
}
Copy after login

Output:

Sorting in Java

2. Collection.reverseOrder()

This method in Java is used to sort the array in reverse order or descending order. There are scenarios where we need to sort the elements in descending order, and Java does that through the built-in method.

Code:

import java.util.Arrays;
public class ReverseSort
{
public static void main(String[] args)
{
//Unsorted array of numbers
Integer[] arr = new Integer[] { 100, 20, 10, 30, 80, 70, 90, 40, 50, 60};
//Sort function to sort the above array
Arrays.sort(arr, Collections.reverseOrder());
//Printing the sorted array on console
System.out.println(Arrays.toString(arr));
}
}
Copy after login

Output:

Sorting in Java

3. sort(int[ ] array_name, int findex, int lindex)

If there is a need to sort some part of an array instead of the whole array, Java provides the facility to sort this type of array by specifying 3 parameters, i.e. array name, first index from where the sorting needs to be started and the last index till when the sorting needs to be done.

Code:

import java.util.Arrays;
public class ReverseSort
{
public static void main(String[] args)
{
//Unsorted array of numbers
Integer[] arr = new Integer[] { 100, 20, 10, 30, 80, 70, 90, 40, 50, 60};
//Sort function to sort the above array
Arrays.sort(arr, 1, 5);
//Printing the sorted array on console
System.out.println(Arrays.toString(arr));
}
}
Copy after login

Output:

Sorting in Java

4. Arrays.parllelSort(array_name)

From Java 8, the new API of the parallel sort has been released. Basically, in Parallel sort, the array is divided into 2 sub-arrays, and then the basic Array.sort() function is performed by a separate thread. The sorted arrays are then merged in the end to form the fully sorted array. This is done to leverage the use of multi-threading.

Code:

import java.util.Arrays;
public class ParallelSort
{
public static void main(String[] args)
{
//Unsorted array of numbers
Integer[] arr = new Integer[] { 100, 20, 10, 30, 80, 70, 90, 40, 50, 60};
//parallel Sort function to sort the above array
Arrays.parallelSort(arr);
//Printing the sorted array on console
System.out.println(Arrays.toString(arr));
}
}
Copy after login

Output:

Sorting in Java

Like a normal Array.sort(), Arrays.parallelSort() also provides the facility to sort a particular range of array or sorting an array in reverse order.

Syntax:

// to Sort a range of array by parallelsort
Arrays.parallelSort(array_name, findex, lindex);
// to sort an array in reverse order using parallelSort
Arrays.parallelSort(array_name, Collections.reverseOder());
Copy after login

5. Collection.sort()

This method is used to sort the collections like list, map, Set, etc. It uses the merge sort and gives the same complexity as Array.sort(), i.e. O(n(logn)).

1. Sorting a List in ascending order

Code:

import java.util.Arrays;
import java.util.Collections;
public class ListSort
{
public static void main(String[] args)
{
//Unsorted list
Integer[] arr = new Integer[] { 100, 20, 10, 30, 80, 70, 90, 40, 50, 60 };
List<Integer> arrList = Arrays.asList(arr);
//Sorting of list using the method
Collections.sort(arrList);
//Printing the list sorted above
System.out.println(arrList);
}
}
Copy after login

Output:

Sorting in Java

2. Sorting an Array List in descending order

Code:

import java.util.Arrays;
import java.util.Collections;
public class ListSortRev
{
public static void main(String[] args)
{
//Unsorted array list of Integers
Integer[] arr = new Integer[] {100, 20, 10, 30, 80, 70, 90, 40, 50, 60 };
List<Integer> arrList = Arrays.asList(arr);
//Sorting of list using the method
Collections.sort(arrList);
//Printing the list sorted above
System.out.println(arrList);
}
}
Copy after login

Output:

Sorting in Java

3. Sorting of Set

There are 3 basic rules while sorting a collection ‘Set’ using the above method sort(array_name):

    1. Convert the Set into the list.
    2. Sort the list using the method sort(array_name).
    3. Convert the resulting sorted List back to Set.

Code:

List<Integer> numList = new ArrayList<Integer>(num) ;
//Sorting the list retrieved above
Collections.sort(numList);
// Converting sorted List into Set
num = new LinkedHashSet<>(numList);
//Printing the Resulting Set on console
System.out.println(num);
}
}
Copy after login

Output:

Sorting in Java

4. Sort a Map

Collection Map in Java is a combination of key and value So sorting can be done both ways, either through key or by value.

  • Sort a Map by Key: Let’s see the below example of Sorting a Map by Key.

Code:

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class SortHashKey
{
public static void main(String[] args)
{
HashMap<Integer, String> map = new HashMap<>();
map.put(80, "Akshay");
map.put(20, "Akash");
map.put(10, "Bob");
map.put(30, "Nitika");
map.put(90, "Yashi");
map.put(100, "Dragisa");
TreeMap<Integer, String> treeMap = new TreeMap<>(map);
System.out.println(treeMap);
}
}
Copy after login

Output:

Sorting in Java

One of the easiest ways to sort the elements of the Map by Keys is by adding the unsorted map elements in the TreeMap. TreeMap automatically sorts the elements in the ascending order of Hash Keys. Though collection.sort() can also be used to do the same, it is somewhat complex and needs to be coded well.

  • Sort a Map by Value: Below mentioned is an example of how the sorting can be done in a Map using value.

Code: 

import java.util.HashMap;
import java.util.Map;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;
public class SortHashValue
{
public static void main(String[] args)
{
HashMap<Integer, String> map = new HashMap<>(); map.put(80, "Akshay");
map.put(20, "Akash");
map.put(10, "Bob");
map.put(30, “Nitika");
map.put(90, "Yashi");
map.put(100, "Dragisa");
LinkedHashMap<Integer, String> sorted = new LinkedHashMap<>(); map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.forEachOrdered(x -> sorted.put(x.getKey(), x.getValue()));
Copy after login

Output:

Sorting in Java

In the above example of sorting of Map by value, firstly we set the entries using the map.entrySet() and then stream of those entries using stream() method, call the sorted array using sorted() method by comparing by value in the pair. for each ordered() is used to traverse the stream to produce the result.

5. Comparable

Comparable is an Interface, and it makes the classes comparable to its instances.

To compare the two instances of the same class, Comparable interface needs to be implemented, and the method compareTo() needs to be overridden. The classes that implement this interface, its list of objects are sorted automatically using the method Collections.sort() and Arrays.sort().

Code:

ArrayList<Employee> list = new ArrayList<>();
// Adding the instance objects of class Employee in list
list.add(new   Employee(10,   "Akshay")));
list.add(new      Employee(40,      "Bob")));
list.add(new  Employee(20,  "Priyansh")));
list.add(new  Employee(50,   "Chandni")));
list.add(new Employee(70, "Yashi")));
Collections.sort(list);
// Printing the sorted list on Console
System.out.println(list);
Copy after login

Output:

Sorting in Java

Conclusion

The Sorting in Java methods used in Java for multiple scenarios of Arrays and Collections are explained above. A programmer needs to keep in mind how the sort() method should be used for different Collection types. With Java 8, sorting can also be done through Lambdas to implement the Comparator interface, which makes the sorting easier. Though it is a bit difficult to learn all of them, it can be easy working with them if all the basic concepts of Java, especially data streaming, Arrays, and Collections, are clear. Though sorting Algorithms are evergreen and can be easily implemented in Java-like other programming languages, they have varying complexity, and the in-built function sort() of Java makes things easier if the basic concepts are learned by heart.

The above is the detailed content of Sorting in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template