Selection Sort
Algorithm
Input Array of integers Output Sorted array Complexity O(n^2). Min_val(a,I,n) This procedure finds the location loc of the smallest element in array a of size n 1. Set min = a[I] and loc = I [Initializes pointers] 2. Repeat step 3 for j = I+1 to n 3. If min>A[j] then: a. Set min=A[j] b. Set loc=j; 4. [end of for loop] 5. Return loc; 6. [end] Selection-sort(a,n)//Sorts the array A with n elements 1. Repeat steps 2 and 3 for i=1 to n-1: 2. Call Min_val(a,i,n) 3. [interchange A[i] and A[loc]] a. Set temp:=A[i]; b. Set A[i] := A[loc]; c. Set A[loc] := temp; 4. [end of step 1 loop] 5. [end]
Algorithm Description
Java Code
import java.io.*;
class selection
{
public static void main(String args[]) throws Exception
{
int temp,n,i,j,small,loc;
BufferedReader cin= new BufferedReader (new InputStreamReader(System.in));
System.out.println("enter the no. of elements");
n=Integer.parseInt(cin.readLine());
int arr[]=new int[n];
System.out.println("enter the elements to be sorted");
for(i=0;i<n;i++)
{
arr[i]= Integer.parseInt(cin.readLine());
}
for(i=1;ilt;n;i++)
{
small=arr[i-1];
loc=i-1;
for(j=i;jlt;n;j++)
{
if(arr[j]lt;small)
{
small=arr[j];
loc=j;
}
}
if(loc!=i-1)
{
temp=arr[i-1];
arr[i-1]=arr[loc];
arr[loc]=temp;
}
}
System.out.println("the elements after sorting are:");
for(i=0;ilt;n;i++)
System.out.println(arr[i]+" ");
}
}