Java program to sort an array of integers in ascending order

Java program to sort an array of integers in ascending order:

In this Java programming tutorial, we will learn how to sort an array of integers in ascending order. Our program will first take the inputs from the user and create one integer array. It will sort the numbers of the array and print it out again to the user.

The size of the array is not fixed, i.e. the user will enter its size before entering the elements. Let’s take a look at the program :

Example 1: Java program to sort an array with loops:

The following program shows how to sort an array of integers in ascending order with two for loops:

import java.util.Arrays;
import java.util.Scanner;

class FirstExample {
    public static void main(String[] args) {
        // 1
        try (Scanner sc = new Scanner(System.in)) {
            int tempValue;

            // 2
            System.out.println("Enter number of array elements:");
            int size = sc.nextInt();

            // 3
            int[] numArray = new int[size];

            // 4
            for (int i = 0; i < size; i++) {
                System.out.print("Enter element: ");
                numArray[i] = sc.nextInt();
            }

            // 5
            System.out.println("You have entered: " + Arrays.toString(numArray));

            // 6
            for (int i = 0; i < numArray.length; i++) {
                for (int j = i + 1; j < numArray.length; j++) {

                    // 7
                    if (numArray[i] > numArray[j]) {
                        tempValue = numArray[i];
                        numArray[i] = numArray[j];
                        numArray[j] = tempValue;
                    }
                }
            }

            // 8
            System.out.println("Array after sorting: " + Arrays.toString(numArray));
        }

    }
}

Download it on GitHub

Explanation:

The commented numbers in the above program denote the step numbers below :

  1. Initialize one Scanner variable sc to read the user input. Also, declare one integer variable tempValue to use as a temp variable.

  2. Ask the user to enter the size of the array. Read it and assign it to the variable size.

  3. Initialize one integer array numArray. The size of the array is equal to the user input size.

  4. It uses a for loop to read the array values. It takes the values as inputs from the user and adds them to the array.

  5. It prints the array content before sorting is started.

  6. This is the main step used for sorting the array. We are using two for loops to sort the array.

    1. The outer loop runs from the first element to the last element of the array.
    2. The inner one will run from the current element pointed by the outer loop to the last element of the array i.e., for each element, the inner loop will iterate over all the elements to its right.
  7. For an element pointed by the outer loop, if any smaller element is found by the inner loop, it swaps these elements. We are using the tempValue variable to temporarily store the value of one number.

  8. Finally, print out the result to the user.

Sample Output:

If you run the above program, it will print outputs as below:

Enter number of array elements:
5
Enter element: 5
Enter element: 4
Enter element: 3
Enter element: 6
Enter element: 2
You have entered:
[5, 4, 3, 6, 2]
Array after sorting:
[2, 3, 4, 5, 6]

java sort array int ascending order

The time complexity of this sort is O(n^2).

Example 2: Sort an array with Arrays.sort:

The Arrays class provides a method to sort an array in ascending numerical order. This method takes one integer array as the parameter, and it sorts all the elements of that array. It uses Dual-Pivot Quicksort, which is faster than the traditional Quicksort algorithm and offers O(n log(n)) time complexity on all data set.

The following program shows how it works:

import java.util.Arrays;
import java.util.Scanner;

class Example {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int tempValue;

        System.out.println("Enter number of array elements : ");
        int size = sc.nextInt();

        int[] numArray = new int[size];

        for (int i = 0; i < size; i++) {
            System.out.print("Enter element : ");
            numArray[i] = sc.nextInt();
        }

        System.out.println("You have entered : ");
        for (int i = 0; i < size - 1; i++) {
            System.out.print(numArray[i] + ",");
        }
        System.out.println(numArray[numArray.length - 1]);

        Arrays.sort(numArray);

        System.out.println("Final array after the sorting : ");
        for (int i = 0; i < size - 1; i++) {
            System.out.print(numArray[i] + ",");
        }
        System.out.println(numArray[numArray.length - 1]);

    }
}

Download it on GitHub

Sample output:

Enter number of array elements:
5
Enter element: 5
Enter element: 4
Enter element: 3
Enter element: 2
Enter element: 1
You have entered: [5, 4, 3, 2, 1]
Final array after the sorting: [1, 2, 3, 4, 5]

Arrays.sort is preferred over other algorithms as it is faster.

Example 3: How to sort an array in a range:

We can pass the start and end index to the Arrays.sort method.

public static void sort(int[] a, int fromIndex, int toIndex)
  • The fromIndex is the index of the element to start the sort(inclusive).
  • The toIndex is the index of the element to stop the sort(exclusive).
  • It throws IllegalArgumentException if fromIndex > toIndex and throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length.

For example:

import java.util.Arrays;

class ThirdExample {
    public static void main(String[] args) {

        int[] numArray = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };

        System.out.println("You have entered: " + Arrays.toString(numArray));

        Arrays.sort(numArray, 2, 6);

        System.out.println("Final array after the sorting: " + Arrays.toString(numArray));

    }
}

Download it on GitHub

The above program will sort the array numArray from index 2 to index 5. It will print the below output:

You have entered: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Final array after the sorting: [10, 9, 5, 6, 7, 8, 4, 3, 2, 1]

Example 4: How to sort a large set of data:

The Arrays class provides a method called parallelSort that uses multiple threads to sort an array. It is preferred over the sort method if the data set is huge. It uses the Dual-Pivot Quicksort algorithm to sort the array in O(n log(n)) complexity.

import java.util.Arrays;

class FourthExample {
    public static void main(String[] args) {

        int[] numArray = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };

        System.out.println("You have entered: " + Arrays.toString(numArray));

        Arrays.parallelSort(numArray);

        System.out.println("Final array after the sorting: " + Arrays.toString(numArray));

    }
}

Download it on GitHub

It will print similar results.

Similar tutorials: