Java program to sort array using Sort method

Program

import java.util.Arrays;
import java.util.Scanner;
public class SortArrayUsingSortMethod {
  public static void main(String[] args) {  
    int i= 0; 
    System.out.println("Enter the required size of the array: ");
    Scanner reader = new Scanner(System.in);
    int size = reader.nextInt();
    int inputArray[] = new int[size];
    System.out.println("Enter the elements of the array: ");
    for (i = 0; i < size; i++) {
      inputArray[i] = reader.nextInt();
    }
    Arrays.sort(inputArray);
    System.out.println("Array elements sorted in ascending order: ");
    for (i = 0; i < inputArray.length; i++) {
      System.out.println(inputArray[i]);
    }
  }
}

This program demonstrates how to sort an array in ascending order using Java's built-in Arrays.sort() method.

  1. Input Handling:

    • The user is prompted to enter the size of the array.
    • The program then accepts the array elements from the user.
  2. Sorting Logic:

    • The Arrays.sort() method is used to sort the array in ascending order.
    • This method works efficiently and sorts the elements in place.
  3. Output:

    • After sorting, the program prints the array elements in ascending order using a for loop.
  4. Key Notes:

    • The Arrays.sort() method is efficient and uses the dual-pivot Quicksort algorithm for int[].

Key Features:

  1. Simplicity:
    • The Arrays.sort() method is easy to use and does not require custom logic for sorting.
  2. Efficiency:
    • Sorting is performed in O(n log n) time complexity.
  3. Built-in Functionality:
  • No need to implement sorting logic manually.
  1. Versatile:
  • Can sort arrays of any primitive type or objects (with a comparator).

Output

javac .\SortArrayUsingSortMethod.java
java SortArrayUsingSortMethod
Enter the required size of the array: 
6
Enter the elements of the array: 
89
23
11
56
45
8
Array elements sorted in ascending order: 
8
11
23
45
56
89