# Selection Sort

## How Selection Sort works:-

Contents

Suppose an Array A with N elements A[1],A[2],A[3]. . . . . . . . .A[N] is in memoer. The selection sort algorithm for sorting works as follows –

first, find the smallest element in the list and put it in the first position then find the second element in the list and put it in the second position and so on……

• Find the location (LOC) of the smallest in the list of N elements A[1], A[2]……..A[N] and then interchange A[LOC] and A[1] then A[1] is sorted.
• Find the location (LOC) of the smallest in the sublist of (N-1) elements A[2], A[3]……..A[N] and then interchange A[LOC] and A[2] the, A[1], A[2] is sorted, since A[1]> A[2].
• Find the location (LOC) of the smallest in the sublist of(N-1) elements. A[N] and then interchange A[LOC] and A[N-1]. then A[1], A[2], A[3]. . . . . .A[N] is sorted. sinceA[1]>A[2]>A[3]>. . . . . . . A[N-1]. hence A[N-1]<A[N]

## Selection Sort algorithm:-

1. Set index =0
2. repeat steps 3 , 4 and 5 while index<N (N is the length of Array)
3. find the minimum element in the array in range (index,N-1)
4. swap Array[index] and minimum value.
5. set index = index+1
6. exit
``````import java.util.*;
public class SelectionSort {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of array");
int n =sc.nextInt();
int[] array = new int[n];
System.out.println("Enter the element of array ");
for(int i=0;i<n;i++) {
array[i] = sc.nextInt();
}
selectionsort(array);
System.out.println("Array after sorting");
for(int i=0;i<n;i++) {
System.out.println(array[i]);
}

}
public static void selectionsort(int array[]) {
int length = array.length;
for(int i=0;i<length-1;i++) {
int index=i;
for(int j=i+1;j<length;j++) {
if (array[j]<array[index]){
index=j;
}}
int min = array[index];
array[index]=array[i];
array[i] = min;

}}}
``````