Ascending Order in Java

This program sorts an integer array in ascending order using a simple sorting algorithm called bubble sort.

  • The program first declares an integer array a with some initial values.
  • The program then prints the array before sorting using Arrays.toString(a) and stores the result in a string.
  • The program then initializes a temporary variable temp which will be used to swap elements during the sorting process.
  • The program then uses two nested for loops to compare each element in the array with every other element to its right. For each iteration of the outer loop, the inner loop starts at the next element to the right of the current element and iterates until the end of the array. For each iteration of the inner loop, the program compares the current element with the next element. If the current element is greater than the next element, the program swaps their positions using the temp variable.
  • After the sorting process is complete, the program prints the sorted array using Arrays.toString(a) and stores the result in a string.

Source Code

import java.util.Arrays;
public class ascendingOrder {
    public static void main(String args[])
        // Ascending order
        int[] a = new int[]{8, 2, 9, 7, 33, 3, 87};
        System.out.println("Before Sort : "+Arrays.toString(a));
        int temp;
        for(int i=0;i<a.length;i++)
            for(int j=i+1;j<a.length;j++)
        System.out.println("After Sort : "+Arrays.toString(a));


Before Sort : [8, 2, 9, 7, 33, 3, 87]
After Sort : [2, 3, 7, 8, 9, 33, 87]
To download raw file Click Here

Basic Programs