Selection Sort

Selection Sort is a simple comparison-based sorting algorithm. It works by repeatedly finding the minimum element from the unsorted part of the list and moving it to the beginning. he algorithm maintains two subarrays in a given array The subarray which is already sorted and The subarray which is unsorted during each iteration, the minimum element from the unsorted subarray is selected and swapped with the leftmost unsorted element, moving the boundary of the sorted subarray one element to the right.


Algorithm:

Bubble Sort Visualization
Complexity
Best Time Complexity O(n2)
Average Time Complexity O(n2)
Worst Time Complexity O(n2)
Space Complexity O(1)

Selection Sort Visualizer

Selection Sort Code

public static void selectionSort(int[] arr) {
                        int n = arr.length;
                        for (int i = 0; i < n - 1; i++) {
                            int minIdx = i;
                            for (int j = i + 1; j < n; j++) {
                                if (arr[j] < arr[minIdx]) {
                                    minIdx = j;
                                }
                            }
                            int temp = arr[minIdx];
                            arr[minIdx] = arr[i];
                            arr[i] = temp;
                        }
                    }
                
void selectionSort(int arr[], int n) {
                        for (int i = 0; i < n-1; i++) {
                            int minIdx = i;
                            for (int j = i+1; j < n; j++) {
                                if (arr[j] < arr[minIdx]) {
                                    minIdx = j;
                                }
                            }
                            int temp = arr[minIdx];
                            arr[minIdx] = arr[i];
                            arr[i] = temp;
                        }
                    }
                    
void selectionSort(int arr[], int n) {
                        for (int i = 0; i < n-1; i++) {
                            int minIdx = i;
                            for (int j = i+1; j < n; j++) {
                                if (arr[j] < arr[minIdx]) {
                                    minIdx = j;
                                }
                            }
                            swap(arr[minIdx], arr[i]);
                        }
                    }
def selection_sort(arr):
                        n = len(arr)
                        for i in range(n):
                            min_idx = i
                            for j in range(i+1, n):
                                if arr[j] < arr[min_idx]:
                                    min_idx = j
                            arr[i], arr[min_idx] = arr[min_idx], arr[i]
                    

Practice Questions

Question Number Question Title Level Link
1 Sort an Array Easy Link
2 Sort List Medium Link
3 Valid anagrams Hard Link