How Selection Sort works:-
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:-
- Set index =0
- repeat steps 3 , 4 and 5 while index<N (N is the length of Array)
- find the minimum element in the array in range (index,N-1)
- swap Array[index] and minimum value.
- set index = index+1
- 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;
}}}
![selection sort](https://thecodedata.com/wp-content/uploads/2023/06/image-62.png)
Similar Java Tutorials
- Odd Even in Java
- Method to print exception information in Java
- Exception Handling by Using try-catch in Java
- Checked Exception vs Unchecked Exception
- Exception Hierarchy in Java
- Java Exception Handling Interview Questions
- final finally finalize in java
- User Defined Exception in Java
- Exception Handling Keyword in Java
- throw throws in Java
- try with multiple catch block in Java
- Threads in Java
- Thread priority in Java
1 thought on “Selection Sort”