In this program, the goal is to sort the given array in ascending order. This can be accomplished by using two loops. The outer loop selects an element, and the inner loop compares the selected element with the remaining elements in the array. Through this iterative process, the elements are rearranged from smallest to largest, resulting in the desired ascending order.
In this program, the objective is to sort the given array in ascending order. The sorting process ensures that the smallest element appears on the extreme left (in this case, 1), while the largest element appears on the extreme right (in this case, 8).
Algorithm for a Java code to sort the elements of an array in ascending order
STEP 1: START
STEP 2: Initialize the array arr[] with values {5, 2, 8, 7, 1}
STEP 3: Set the variable temp to 0
STEP 4: Print the message “Elements of Original Array”
STEP 5: Repeat steps 6 to 7 until i is less than the length of arr[]
// for(i=0; i<arr.length; i++)
STEP 6: Print the value of arr[i]
STEP 7: Repeat steps 8 to 9 until i is less than the length of arr[]
// for(i=0; i<arr.length; i++)
STEP 8: Repeat steps 9 to 10 until j is less than the length of arr[]
// for(j=i+1; j<arr.length; j++)
STEP 9: Check if arr[i] is greater than arr[j] – If true, swap the values: – Set temp to the value of arr[i] – Set arr[i] to the value of arr[j] – Set arr[j] to the value of temp
STEP 10: Print a new line
STEP 11: Print the message “Elements of the array sorted in ascending order”
STEP 12: Repeat step 13 until i is less than the length of arr[] // for(i=0; i<arr.length; i++)
STEP 13: Print the value of arr[i]
STEP 14: END
Java Code to sort the elements of an array in ascending order
public class SortAsc { public static void main(String[] args) { //Initialize array int [] arr = new int [] {5, 2, 8, 7, 1}; int temp = 0; //Displaying elements of original array System.out.println("Elements of original array: "); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } //Sort the array in ascending order for (int i = 0; i < arr.length; i++) { for (int j = i+1; j < arr.length; j++) { if(arr[i] > arr[j]) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } System.out.println(); //Displaying elements of array after sorting System.out.println("Elements of array sorted in ascending order: "); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } }
Output:
Elements of original array: 5 2 8 7 1 Elements of array sorted in ascending order: 1 2 5 7 8
In conclusion, the provided Java code effectively sorts the elements of an array in ascending order. By utilizing two loops, the elements are compared and swapped iteratively, resulting in the desired arrangement from smallest to largest. Follow tutorials.freshersnow.com to learn more.