Java program for Sorting Elements In An Array

Java Program for Sorting Elements

In this article we will learn Java Program for Sorting Elements. Sorting is a very widely used technique in an array. To sort an array in java we have to compare every given elements with all the remaining element to check whether it is greater, if so we have to swap them

One solution to do so you need to use nested loops where the inner loop starts with i+1 (where i is the variable of outer loop) to avoid repetitions in comparison

Sorting element in array by frequency using C++
Sort Element Of An Array in Java

Algorithms-

  • STEP 1: START
  • STEP 2: INITIALIZE arr[] ={5, 3, 9, 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
import java.util.Arrays;
import java.util.Scanner;
public class test {

public static void main(String[] args) {
//Initialize array
Scanner input = new Scanner (System.in);

int[] arr = new int[5];

//Displaying elements of original array
System.out.println("Elements are not of original array");
//input for the arrays
for (int i = 0;i< arr.length; i++) {

//calling the nextInt for appending the element in the arrays
arr[i]=input.nextInt();

}

// calling the sort function for sorting the inputed array
sort(arr);

//Displaying elements of array after sorting
System.out.println("Elements of array sorted in ascending order:" + Arrays.toString(arr));
}
//Sort the array in ascending order
static void sort(int[]arr) {
//added boolean for edge cases
boolean swapped =true;
// loop for looping into the array and getting a element
for(int i =0 ; i< arr.length;i++) {
swapped = false;
// looping through the each index and sorting the element
for (int j =1; j<arr.length-i;j++) {
// method for swapping the numbers if they are
if(arr[j] < arr[j-1]) {
//swapping the text
int temp = arr[j];
arr[j]=arr[j-1];
arr[j-1]=temp;
swapped =true;
}
}
if (!swapped) {
break;
}
}
}
}
output-
Elements are not of original array 12 2 34 1 3 Elements of array sorted in ascending order:[1, 2, 3, 12, 34]
output- 
Elements are not of original array 1
3
2
4
7
Elements of array sorted in ascending order:[1, 2, 3, 4, 7]