Sort subset of array elements in Java

Java 8Object Oriented ProgrammingProgramming

The java.util.Arrays.sort() method can be used to sort a subset of the array elements in Java. This method has three arguments i.e. the array to be sorted, the index of the first element of the subset (included in the sorted elements) and the index of the last element of the subset (excluded from the sorted elements). Also, the Arrays.sort() method does not return any value.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.Arrays;
public class Demo {
   public static void main(String[] args) {
      int arr[] = { 1, 9, 7, 3, 2, 8, 4, 6, 5};
      System.out.print("The original array is: ");
      for (int i : arr) {
         System.out.print(i + " ");
      }
      Arrays.sort(arr, 2, 8);
      System.out.print("\nThe array after its subset is sorted is: ");
      for (int i : arr) {
         System.out.print(i + " ");
      }
   }
}

output

The original array is: 1 9 7 3 2 8 4 6 5
The array after its subset is sorted is: 1 9 2 3 4 6 7 8 5

Now let us understand the above program.

First the array arr is defined and then printed using a for loop. A code snippet which demonstrates this is as follows −

int arr[] = { 1, 9, 7, 3, 2, 8, 4, 6, 5};
System.out.print("The original array is: ");
for (int i : arr) {
   System.out.print(i + " ");
}

Then the Arrays.sort() method is used to sort the subset of the array from index 2 to index 8. The element at index 2 is included in the sorting while the element at index 8 is not. Then the array with the sorted subset is displayed using a for loop. A code snippet which demonstrates this is as follows −

Arrays.sort(arr, 2, 8);
System.out.print("\nThe array after its subset is sorted is: ");
for (int i : arr) {
   System.out.print(i + " ");
}
raja
Published on 09-Jan-2019 10:11:03
Advertisements