Java - How To Sort An Array Only In Specific Index Range?
Maybe your like
Sort Array in Specific Index Range
To sort an array only in specified index range, you can call Arrays.sort() method and pass the arguments: array, starting-index and to-index to the method.
The syntax of Arrays.sort() method to sort only in the given index range is
</> Copy sort(arr, fromIndex, toIndex)where
- arr is the array of elements. The array could be of type byte, char, double, integer, float, short, long, object, etc.
- fromIndex is an integer representing the index of array from which sorting has to start.
- toIndex is an integer representing the index up till which sorting has to be done. toIndex is not included in the sorting range. Only till the element before this index is included in sorting process.
Example – Sort an Array in Specific Index Range
In the following program, we will take an integer array with seven elements. So, the index range of this array is 0 to 6.
We will sort only the elements present in the index range [1, 4). So only the elements in the range 1-3 will be sorted in ascending order.
Elements outside of the specified index range remain unchanged.
Java Program
</> Copy import java.util.Arrays; public class Example2 { public static void main(String[] args) { int arr[] = {2, 14, 5, 8, 7, 9, 0}; int fromIndex = 1; int toIndex = 4; Arrays.sort(arr, fromIndex, toIndex); System.out.println(Arrays.toString(arr)); } }Output
[2, 5, 8, 14, 7, 9, 0]Detailed Explanation
Given input array is {2, 14, 5, 8, 7, 9, 0}.
The range of index in which sorting has to happen is [1, 4). 4 is not included in the range.
arr [2, 14, 5, 8, 7, 9, 0] index 0 1 2 3 4 5 6 |--------| these elements will be sorted sorted array [2, 5, 8, 14, 7, 9, 0]Conclusion
In this Java Tutorial, we learned how to sort an array only for the specified index range, with the help of example programs.
Tag » How To Sort Java Array
-
rt() In Java With Examples - GeeksforGeeks
-
How To Sort An Array In Java - Javatpoint
-
How To Sort An Array In Java - Tutorial With Examples
-
Java.util.rt(int[]) Method - Tutorialspoint
-
How To Sort An Array In Java - Video & Lesson Transcript
-
Sort An Array In Java - Stack Overflow
-
What Is Sort Array In Java: Everything You Need To Know | Simplilearn
-
Arrays (Java Platform SE 7 ) - Oracle Help Center
-
Arrays (Java SE 11 & JDK 11 ) - Oracle Help Center
-
Java Sort Array – How To Reverse An Array In Ascending Or ...
-
How To Sort An Array In Descending Order In Java? Example Tutorial
-
How To Use The rt() Method In Java
-
How To Sort An Array In Java - Code |Interviewkickstart
-
How To Sort An Array In Java Without Using The Sort() Method