Sorting a section of an array

In this post I will explain how to sort a section of an array.

The java Arrays class provides a static method named “sort” which takes the below three arguments
1) the array
2) fromIndex
3) toIndex

This method sorts a section of the array. The section to be sorted is indicated by fromIndex (position indicated by fromIndex is also included)
and toIndex (position indicated by toIndex is excluded).

Below is the complete code

Main Code


1  package collections;
2  
3  import java.util.Arrays;
4  
5  public class ArraysDemo1 {
6   public static void main(String[] args) {
7       int[] array = {5,7,0,2,4,3,9,1,6,8};
8       Arrays.sort(array, 1, 4);
9       for(int i = 0; i < array.length; i++) {
10          System.out.print(array[i] + ",");
11      }
12  }
13 }

Explanation

At line 8, we call the sort method passing the array, fromIndex as 1, and toIndex as 4.

The fromIndex as 1 and toIndex as 4 define the section of the array starting from position 1 (included) to position 3 (excluding position 4).

Output

5,0,2,7,4,3,9,1,6,8,

Leave a Reply