In this post, we will learn how to implement Selection Sort in java. First, we will start by understanding the Selection sort algorithm.
Selection Sort Algorithm
The selection sort is a simple sorting algorithm which is an in-place comparison-based algorithm. It has two parts where the left end has a sorted part and the right end has an unsorted part.
In the beginning, the left end is empty and the right end has all the elements then the smallest element from the right end is brought to the left end and swapped with the leftmost element. This process continues until the element from the right end is brought to the left by swapping.
Although, it may cause a problem with the large inputs.
Before we begin, you need to have an idea of the following:
Time Complexity of Selection Sort:
- Best case:
0(n^2)
- Average case:
0(n^2)
- Worst case:
0(n^2)
Implementation of selection sort in java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | import java.util.Arrays; public class Main { public static int[] selectionSort(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { int index = i; for (int j = i + 1; j < arr.length; j++) { if (arr[j] < arr[index]) index = j; } int smallerNumber = arr[index]; arr[index] = arr[i]; arr[i] = smallerNumber; } return arr; } public static void main(String a[]) { int[] arr = { 25, 5, 12, 60, 2, 1 }; System.out.println("Array Before Sorting: "); System.out.println(Arrays.toString(arr)); arr = selectionSort(arr); System.out.println("Array After Sorting: "); System.out.println(Arrays.toString(arr)); } } |
The output of the Selection sort algorithm in java: