Java program to sort integers in unsorted array


Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way to arrange data in a particular order (ascending or descending).

Problem Statement

For a given array write Java program to sort integers in unsorted array. Consider the following example -

Input

The unsorted integer array = [10, 14, 28, 11, 7, 16, 30, 50, 25, 18]

Output

The unsorted integer array = [10, 14, 28, 11, 7, 16, 30, 50, 25, 18]
The sorted integer array = [7, 10, 11, 14, 16, 18, 25, 28, 30, 50]

Sorting Integers in Unsorted Array

    Step-1: Initialize with unsorted array by declaring and initializing an integer array arr with the given values.

    Step-2: Use Arrays.toString(arr) to convert the array to a string and print it.

    Step-3: Assign the reference of arr to a new array reference res.

    Step-4: Call Arrays.sort(res) to sort the array in ascending order.

    Step-5: Use Arrays.toString(res) to convert the sorted array to a string and print it.

Java program to sort integers in unsorted array

import java.util.Arrays;
public class Demo {
    public static void main(String[] args) {
    int[] arr = { 10, 14, 28, 11, 7, 16, 30, 50, 25, 18};
    System.out.println("The unsorted integer array = "+Arrays.toString(arr));
    int[] res = arr;
    Arrays.sort(res);
    System.out.println("The sorted integer array = "+Arrays.toString(res));
    }
}

Output

The unsorted integer array = [10, 14, 28, 11, 7, 16, 30, 50, 25, 18]
The sorted integer array = [7, 10, 11, 14, 16, 18, 25, 28, 30, 50]

Code Explanation

The Array class from the java.util package is imported to use the Arrays.sort method. A class named Demo is defined with the main method, which is the entry point of the program.

An integer array arr is initialized with unsorted values.

int[] arr = { 10, 14, 28, 11, 7, 16, 30, 50, 25, 18};

The unsorted array is printed using Arrays.toString(arr).The reference of the unsorted array arr is assigned to a new array reference res. Note that both arr and res point to the same array in memory. The Arrays.sort(res) method is called to sort the array in ascending order.

int[] res = arr;
Sorting the integers:
Arrays.sort(res);

Since res and arr reference the same array, sorting res also sorts arr. The sorted array is printed using Arrays.toString(res).

Updated on: 28-Jun-2024

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements