Sample Input 1:
5
1 5 3 2 6
Sample Output 1:
Sorted Array ->
1 2 3 5 6
import java.util.Scanner;
public class SelectionSort {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n=s.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=s.nextInt();
}
selectionSort(a);
print(a);
}
public static void print(int a[])
{
System.out.println("Sorted Array -> ");
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
}
public static void selectionSort(int[] arr) {
int l=arr.length;
for(int i=0;i<l-1;i++)
{
int min=Integer.MAX_VALUE;
int minIndex=-1;
int t=0;
for(int j=i;j<l;j++)
{
if(arr[j]<min)
{
min=arr[j];
minIndex=j;
}
}
t=arr[minIndex];
arr[minIndex]=arr[i];
arr[i]=t;
}
}
}
Comments
Post a Comment