Back to DSA Course

DSA Course

Selection sort is combination of searching and sorting.

It sorts the array by repeatedly finding the minimum element from unsorted part and putting it at the beginning until the sorting is achieved.

For example,

int[] num = { 90, 24, 46, 35, 32 };

Lets see how selection sort works

90,24,46,35,32 24,90,46,35,32 24,32,46,35,90 24,32,35,46,90

Let's start coding for selection sort

package com.praveen.sort; import java.util.Arrays; public class SelectionSort { public static void main(String[] args) { int[] arr = { 90, 24, 46, 35, 32 }; selection(arr); System.out.println(Arrays.toString(arr)); } private static void selection(int[] arr) { for (int i = 0; i < arr.length; i++) { // find the max item in the remaining array and swap with correct index int last = arr.length - i - 1; int maxIndex = getMaxIndex(arr, 0, last); swap(arr, maxIndex, last); } } private static void swap(int[] arr, int first, int second) { int temp = arr[first]; arr[first] = arr[second]; arr[second] = temp; } private static int getMaxIndex(int[] arr, int start, int end) { int max = start; for (int i = start; i <= end; i++) { if (arr[max] < arr[i]) { max = i; } } return max; } }

Output

[24, 32, 35, 46, 90]