Menu
Topics Index
...
`

Arrays Sort Test - Java Example Program


Arrays Sort Test
java.util.Arrays;

class ArraysSortTest
{
    public static void main(String arg[])
    {
        int sample[] = {5, 1, 8, 2, 4, 3, 7, 6, 10, 9};
        Arrays.sort(sample, 3, 8); // LINE A
        System.out.print("Array after sorting within specified range is: ");
        for (int temp : sample)
        {
            System.out.print(temp + " ");
        }
        Arrays.sort(sample); // LINE B
        System.out.println();
        System.out.print("Array after sorting all elements is: ");
        for (int temp : sample)
        {
            System.out.print(temp + " ");
        }    
    }
}
OUTPUT

Array after sorting within specified range is: 5 1 8 2 3 4 6 7 10 9
Array after sorting all elements is: 1 2 3 4 5 6 7 8 9 10

DESCRIPTION

At LINE A, the array is sorted in the range [3, 8) i.e. inclusive lower limit and exclusive upper limit. The elements after sorting in the specified range are printed. At LINE B the whole array is sorted. The elements after sorting are printed.

THINGS TO TRY
  • Try changing the sorting range at LINE A. Consider cases like fromIndexgreater than toIndex, fromIndexequal to toIndexand index values out of bounds.
  • Try sorting double array or float array or String array.

© meritcampus 2019

All Rights Reserved.

Open In App