Question
Selection sort or linear sort an unsorted array.
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
import java.util.Scanner;
public class SelectionSortArray
{
public static void main(String args[])
{
int n=0,i=0,j=0,temp=0;
int[] arr;
Scanner sc=new Scanner(System.in);
System.out.println("Enter no. of elements in the array");
n = sc.nextInt();
System.out.println("Enter numbers in array");
arr=new int[n];
for(i=0;i< n;i++)
{
arr[i]=sc.nextInt();
}
System.out.println("Unsorted Array:");
for (i=0; i< n; ++i)
{
System.out.print(arr[i] + " ");
System.out.println();
}
/*Sorting of array*/
for (i = 0; i < n-1; i++)
{
for (j = i+1; j < n; j++)
{
if (arr[i] > arr[j+1])
{
// swap arr[j+1] and arr[i]
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
System.out.println("Sorted Array:");
for (i=0; i< n; i++)
{
System.out.print(arr[i] + " ");
System.out.println();
}
}
}