Arrays.sort() in Java with examples
An array class is a class containing static methods that are used with arrays in order to search, sort, compare, inserting elements, or returning a string representation of an array. in an array. So let us specify the functions first and later onwards we will be discussing the same. They are as follows been present in java.util.Arrays class. Here we will be discussing out different plots using the sort() method of the Arrays class.
Arrays.sort() method consists of two variations one in which we do not pass any arguments where it sort down the complete array be it integer array or character array but if we are supposed to sort a specific part using this method of Arrays class then we overload it and pass the starting and last index to the array.
Syntax: sort() Method
Syntax: Overloaded sort() Method
public static void sort(int arr, int from_Index, int to_Index) ;
Parameters: It takes three parameters as can be perceived from the syntax which is as follows:
- The array to be sorted
- The index of the first element, inclusive, to be sorted (Referred to as from_index)
- The index of the last element, exclusive, to be sorted (Referred to as last_index)
Return Type: It does not return any value.
Now let us see the implementation of the sort() function across different scenarios of the Arrays class as follows:
Modified arr : [6, 7, 9, 13, 21, 45, 101, 102]
Modified arr : [13, 6, 7, 21, 45, 9, 2, 100]
Modified arr : [100, 45, 21, 13, 9, 7, 6, 2]
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.
Unsorted 111 bbbb london 131 aaaa nyc 121 cccc jaipur Sorted by rollno 111 bbbb london 121 cccc jaipur 131 aaaa nyc
Note: There is a slight difference between Arrays.sort() vs Collections.sort(). Arrays.sort works for arrays which can be of primitive data type also. Collections.sort() works for objects Collections like ArrayList, LinkedList, etc.
This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.