Java Code for Selection Sort. Selection sort is a sorting algorithm that iteratively finds the minimum/maximum elements in an unsorted sub-array and swaps with the first element. this process repeats until the entire array is sorted.

## Table of Contents

## Selection Sort Algorithm Breakdown

**Start with the first unsorted element:**Consider this element as the minimum for now.**Compare the current minimum with the rest of the unsorted elements:**If any other element is smaller than the current minimum, update the minimum index.**Swap the current minimum with the element it indexes:**This places two minimum elements in its correct sorted position.**Repeat Steps 2 and 3 for the remaining unsorted array:**Increment the sorted position by 1 and repeat the comparison and swapping process for the remaining elements.

## Java Program for Selection Sort

Below is a simple Java program that implements the selection sort algorithm to sort an array of integers in ascending order.

```
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.print(array[i] + " ");
}
}
public static void selectionSort(int array[]) {
int length = array.length;
for(int i=0;i<length-1;i++) {
int minIndex=i;
for(int j=i+1;j<length;j++) {
if (array[j]<array[minIndex]){
minIndex=j;
}}
int min = array[minIndex];
array[minIndex]=array[i];
array[i] = min;
}}}
```

### Output

## Key Points to Remember for the Selection Sort Algorithm

**In place and not stable:**Selection sort is an in-place sorting algorithm. However, it can be made stable with some modifications.**Time Complexity:**The time complexity of the selection sort algorithm is`O(n^2)`

, where n is the number of elements in the array. The time complexity of quick sort makes it inefficient for large datasets.**Space Complexity:**The selection sort has a space complexity of`O(1)`

, which means it requires a constant, small amount of additional storage space.

Selection sorting is particularly useful for small arrays or as an educational tool to learn about sorting algorithms. Its simplicity and the fact that it uses a minimum number of swaps can be advantages in certain scenarios, despite its overall inefficiency compared to more complex algorithms.

*Happy Coding & Learning*

## 3 thoughts on “Java Code for Selection Sort”