Skip to main content

Practical-12

Write a Java Program to sort the elements of an array in Ascending Order.

Introdution

This program demonstrates how to sort the elements of an array in ascending order using the Java programming language. This program requires a few simple steps, starting with declaring an array and using the sorting algorithm to perform the actual sorting operation. The sorting algorithm used in this program is the Selection Sort algorithm as it is one of the most commonly used and easiest algorithms to understand. Furthermore, this program also has a few other simple features such as user input and displaying the sorted array to the console.

Code

//Java program to sort array elements in ascending order.
public class AscendingOrder {
public static void main(String args[]) {
//declaring an array
int arr[] = {4, 55, 2, 3, 9};

//sorting 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])
{
//swapping the elements
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

//displaying sorted array elements
System.out.print("Sorted array elements:\n");
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");
}
}

Output

Sorted array elements:
2 3 4 9 55
Explanation

This code uses the Selection Sort algorithm to sort an array of integers in ascending order. The sorting algorithm first iterates through the array, comparing each element to its successor and swapping them if the element is greater than its successor. After the comparison and swap between elements is complete for each iteration of the loop, the array is now sorted in ascending order.