Java Program to sort the elements of an array in ascending order

In this program, we need to sort the given array in ascending order such that elements will be arranged from smallest to largest. This can be achieved through two loops. The outer loop will select an element, and inner loop allows us to compare selected element with rest of the elements.

Java Program to sort the elements of an array in ascending order

Elements will be sorted in such a way that the smallest element will appear on extreme left which in this case is 1. The largest element will appear on extreme right which in this case is 8.

Algorithm

  • STEP 1: START
  • STEP 2: INITIALIZE arr[] ={5, 2, 8, 7, 1 }.
  • STEP 3: SET temp =0
  • STEP 4: PRINT “Elements of Original Array”
  • STEP 5: REPEAT STEP 6 UNTIL i<arr.length
                //for(i=0; i<arr.length; i++)
  • STEP 6: PRINT arr[i]
  • STEP 7: REPEAT STEP 8 to STEP 9 UNTIL i<arr.length
                //for(i=0; i<arr.length; i++ )
  • STEP 8: REPEAT STEP 9 UNTIL j<arr.length
                //for(j=i+1;j<arr.length;j++)
  • STEP 9: if(arr[i]>arr[j]) then
                temp = arr[i]
                arr[i]=arr[j]
                arr[j]=temp
  • STEP 10: PRINT new line
  • STEP 11: PRINT “Elements of array sorted in ascending order”
  • STEP 12: REPEAT STEP 13 UNTIL i<arr.length
                //for(i=0;i<arr.length;i++)
  • STEP 13: PRINT arr[i]
  • STEP 14: END

Program:

  1. public class SortAsc {    
  2.     public static void main(String[] args) {        
  3.             
  4.         //Initialize array     
  5.         int [] arr = new int [] {5, 2, 8, 7, 1};     
  6.         int temp = 0;    
  7.             
  8.         //Displaying elements of original array    
  9.         System.out.println(“Elements of original array: “);    
  10.         for (int i = 0; i < arr.length; i++) {     
  11.             System.out.print(arr[i] + ” “);    
  12.         }    
  13.             
  14.         //Sort the array in ascending order    
  15.         for (int i = 0; i < arr.length; i++) {     
  16.             for (int j = i+1; j < arr.length; j++) {     
  17.                if(arr[i] > arr[j]) {    
  18.                    temp = arr[i];    
  19.                    arr[i] = arr[j];    
  20.                    arr[j] = temp;    
  21.                }     
  22.             }     
  23.         }    
  24.           
  25.         System.out.println();    
  26.             
  27.         //Displaying elements of array after sorting    
  28.         System.out.println(“Elements of array sorted in ascending order: “);    
  29.         for (int i = 0; i < arr.length; i++) {     
  30.             System.out.print(arr[i] + ” “);    
  31.         }    
  32.     }    
  33. }    

Output:

Elements of original array:
5 2 8 7 1
Elements of array sorted in ascending order:
1 2 5 7 8    

Leave a Comment