How to perform selection sort in java ?

Sorting mean that to arrange the element in ascending or descending order. In java there are many ways to perform sorting.
Selection sort is one of them used for sorting. In selection sort we find the smallest value and swap from the first value and again second smallest value is swapped with second value.This process continues until the array is sorted.

Code for selection sort in java-:

package array;
public class selection
{
public static void main(String[ ] args)
{
System.out.print(“Element in Unsorted form-: “);
int [ ] a = {1, -3, 5, -9, -2};
for (int i = 0; i <= a.length – 1; i++)
{
System.out.print(a[ i ] + ” “);
}
System.out.println(“”);
for (int i = 0; i <= a.length – 2; i++)
{
int min = a[ i ];
int pos = i;
for (int j = i + 1; j <= a.length – 1; j++)
{
if (a[ j ] < min)
{
min = a[ j ];
pos = j;
}
}
int temp = a[ i ];
a[ i ] = a[pos];
a[pos] = temp;
}
System.out.print(“Element in Sorted form-: “);
for (int r = 0; r <= a.length – 1; r++)
{
System.out.print(a[ r ] + ” “);
}
System.out.println(“”);
}
}

Output -:

Leave a Reply