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;
3  import java.util.Arrays;
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 }


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).




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s