Sorting algorithms are fundamental in computer science, and Selection Sort is one of the simplest techniques. It works by repeatedly selecting the smallest (or largest) element from an unsorted list and placing it in its correct position in a sorted list.
This article covers:
Selection Sort follows a comparison-based technique where it selects the smallest (or largest) element from the unsorted portion and swaps it with the first unsorted element. This process continues until the entire array is sorted.
Let’s sort the array [14, 16, 3, 6, 50]
in ascending order using Selection Sort.
Iteration | Array State | Explanation |
---|---|---|
Start | [14, 16, 3, 6, 50] | Initial unsorted array |
Step 1 | [3, 16, 14, 6, 50] | Swap 3 (smallest) with 14 |
Step 2 | [3, 6, 14, 16, 50] | Swap 6 with 16 |
Step 3 | [3, 6, 14, 16, 50] | 14 is already in place |
Step 4 | [3, 6, 14, 16, 50] | 16 is already in place |
Sorted Array | [3, 6, 14, 16, 50] | Final sorted array |
Here’s the basic logic behind Selection Sort:
plaintextCopyEditfor i = 0 to n - 1:
min_index = i
for j = i + 1 to n:
if arr[j] < arr[min_index]:
min_index = j
Swap arr[min_index] with arr[i]
Below are the implementations of Selection Sort in different programming languages.
cCopyEdit#include <stdio.h>
void selectionSort(int arr[], int n) {
int i, j, min_index, temp;
for (i = 0; i < n - 1; i++) {
min_index = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[min_index])
min_index = j;
}
temp = arr[min_index];
arr[min_index] = arr[i];
arr[i] = temp;
}
}
cppCopyEdit#include <iostream>
using namespace std;
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int min_index = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_index])
min_index = j;
}
swap(arr[min_index], arr[i]);
}
}
javaCopyEditpublic class SelectionSort {
public static void selectionSort(int arr[]) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int min_index = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_index])
min_index = j;
}
int temp = arr[min_index];
arr[min_index] = arr[i];
arr[i] = temp;
}
}
}
Case | Time Complexity | Explanation |
---|---|---|
Best Case (Already Sorted Array) | O(N²) | Still performs N² comparisons |
Average Case | O(N²) | Comparisons remain the same for random input |
Worst Case (Reverse Sorted Array) | O(N²) | Maximum swaps occur |
Feature | Selection Sort | Bubble Sort |
---|---|---|
Time Complexity (Worst/Average Case) | O(N²) | O(N²) |
Best Case Complexity | O(N²) | O(N) |
Number of Swaps | O(N) (Better) | O(N²) (Worse) |
In-place? | Yes | Yes |
Stable? | No | Yes |
For more efficient sorting, check out: