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.