Sort int Array Java

Many times, in any programming language, sorting of data either in a DS or an array is required. In C/C++, it requires good logic and lengthy code of iterations. In many places in this Web site, I said Java is simple to practice avoiding lot of lines of code. This tutorial on Sort int Array proves it.

For all DS elements operations and array elements operations, Java Designers gifted two concrete classes from java.util package – class Collections and class Arrays. These classes contain static methods so that their methods can be called without object; just call with class name.

Following example on Sort int Array gives two styles: sorting all the elements or a few elements between two given index numbers. The method used is sort() from java.util.Arrays class
import java.util.Arrays;
public class SortArray
  public static void main(String args[])
  {                                                   // SORTING ALL ELEMENTS
    int num1[] = { 40, 80, 10, 45, 12, 89, 32 };
    System.out.println("Elements before sorting: " + Arrays.toString(num1));
    Arrays.sort(num1);                                // sorts all array elements
    System.out.println("All Elements after sorting: " + Arrays.toString(num1));
    int num2[] = { 400, 800, 100, 450, 120, 890, 320, 345 };
    System.out.println("\nElements before sorting: " + Arrays.toString(num2));
    Arrays.sort(num2, 2, 6);                          // sorts from index numbers 2 to 5 (6-1)
    System.out.println("2, 3, 4, 5 Elements after sorting: " + Arrays.toString(num2));

Sort int Array JavaOutput Screenshot on Sort int Array Java Java

Arrays.sort(num1): Sorts all elements of the array
Arrays.sort(num2, 2, 6): Sorts a few elements from 2nd element to 5th element (6-1). That is, other than 2, 3, 4 and 5 elements are unaffected in sorting.

To know more details on this same topic like method signatures etc., see this link: Array elements with sort()

Array operations using class java.util.Arrays

Leave a Comment

Your email address will not be published.