Write a program to Sort an array in ascending order using selection sort


This is a Java program that implements the selection sort algorithm to sort an array of integers in ascending order.

The program initializes an array of integers named a with 10 elements. It then uses a while loop with an outer loop variable i to traverse the array from the beginning to the end. The inner loop, with a loop variable j, searches for the minimum value in the remaining unsorted portion of the array.

If the value of the element at index j is less than the value of the element at index min, the program sets the value of min to j. Once the minimum value is found, the program swaps it with the element at the current index i.

This process repeats until the entire array is sorted in ascending order. Finally, the program uses another while loop to display the sorted array.

Source Code

public class Ascending_SelectionSort
{
	public static void main(String[] args)
	{
		int i = 0;
		int j = 0;
		int t = 0;
		int min = 0;
		int a[] = {2, 65, 23, 13, 18, 30, 46, 17, 52, 78};
 
		while(i < 10)
		{
			min = i;
			j = i + 1;
 
			while(j < 10)
			{
				if(a[j] < a[min])
				min = j;
				j = j + 1;
			}
 
			t = a[i];
			a[i] = a[min];
			a[min] = t;
 
			i = i + 1;
		}
 
		System.out.println("Sorted Array in Ascending Order ..");
 
		i = 0;
		while(i < 10)
		{
			System.out.print(a[i] + " ");
			i = i + 1;
		}
	}
}

Output

Sorted Array in Ascending Order ..
2 13 17 18 23 30 46 52 65 78

Example Programs