What is an Array?
- Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
- To declare an array, define the variable type with square brackets:
- We have now declared a variable that holds an array of strings. To insert values to it, we can use an array literal – place the values in a comma-separated list, inside curly braces:
Arrays.sort() in java
- The sorting may be a way to arrange elements of a list or array during a certain order.
- The order could also be in ascending or descending order.
- The numerical and lexicographical (alphabetical) order may be a widely used order.
- sort() method is a java.util.Arrays class method.
- arr – The array to be sorted.
- from_Index – The indexof the first element, inclusive, to be sorted.
- to_Index – The index of the last element, exclusive, to be sorted.
This method doesn’t return any value.
Sort an array of integers in ascending order.
- The ascending order arranges the elements within the lowest to highest order. It’s also referred to as natural order or numerical order
Use sort() to sort a subarray of arr
- An array derived from the array is understood as subarray. Suppose, a is an array having the elements [12, 90, 34, 2, 45, 3, 22, 18, 5, 78] and that we want to sort array elements from 34 to 18. It’ll sort the subarray [34, 2, 45, 3, 22, 18] and keep the other elements because it is.
- To sort the subarray, the Arrays class provides the static method named sort(). It sorts the required range of the array into ascending order. We will also sort the array of type long, double, float, char, byte, etc.
The method parses the following three parameters:
- a: An array to be sort.
- fromIndex: The index of the primary element of the subarray. It participates within the sorting.
- toIndex: The index of the last element of the subarray. It doesn’t participate within the sorting.
Sort Array in Descending Order
- The descending order arranges the elements within the highest to lowest order.
We can also sort strings in alphabetical order
We can also sort an array according to user defined criteria
- We use Comparator interface for this purpose.