Sort Long Array in Java



In this article, we will sort a long array in Java. We will be using the Arrays.sort() method of Arrays class which is present in java.util package. It will helps us to organize data in ascending order, making it easier to use. We'll start with an unsorted array, display it, sort it using Java's built-in method, and then display the sorted array. 

Problem Statement

Given an unsorted array of long numbers write a Java program to sort the unsorted array.

Input

Unsorted long array: 987, 76, 5646, 96,8768, 8767

Output

Sorted long array:
76
96
987
5646
8767
8768

Steps to sort the long Array

Following are the steps to sort the long Array ?

  • We import the java.util package to use the Arrays class.
  • Initialize the Demo class in that there is a main class from where the program starts execution.
  • We initialize a long array with predefined values.
  • A for-each loop is used to print each element of the array before sorting.
  • The Arrays.sort(arr) method is called to sort the array. 
  • Another for-each loop prints each element of the sorted array to display the final sorted result.

Java program to sort long Array

Below is an example of sorting a long Array ?

import java.util.*;
public class Demo {
   public static void main(String []args) {
      long[] arr = new long[] { 987, 76, 5646, 96,8768, 8767 };
      System.out.println("Unsorted long array:");
      for (long l : arr) {
         System.out.println(l);
      }
      System.out.println("Sorted long array:");
      Arrays.sort(arr);
      for (long l : arr) {
         System.out.println(l);
      }
   }
}

Output

Unsorted long array:
987
76
5646
96
8768
8767
Sorted long array:
76
96
987
5646
8767
8768

Code Explanation

In this Java program we have imported the Arrays class from java.util package to use the Arrays.sort() method. It defines the main class Demo and the main method where execution begins. A long array is initialized with predefined values to display the initial unsorted array a for-each loop iterates over each element printing them one by one. After that the Arrays.sort(arr) method is called to sort the array in ascending order. After sorting another for-each loop prints each element of the now sorted array, showing the result clearly. 

Updated on: 2024-08-30T11:43:14+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements