Article written by RIshabh Dev Choudhary, under the guidance of Thomas Gilmour, Ex-LinkedIn and PayPal leader turned engineering coach, mentoring 100+ engineers into FAANG+ roles. Reviewed by Mrudang Vora, an Engineering Leader with 15+ years of experience.
Selection sort works by repeatedly finding the smallest element in the unsorted portion of an array and swapping it into its correct position. What sets it apart from other O(n²) algorithms is that it always makes exactly O(n) swaps regardless of the input order, making it a practical choice in scenarios where memory write operations are expensive.
This article covers how selection sort works, a full pass-by-pass dry run, Python, Java, and C++ code, a detailed complexity breakdown explaining why all three cases are O(n²), and a comparison against insertion sort and bubble sort.
Selection sort is a comparison-based sorting algorithm that divides the array into two logical sub-arrays: a sorted portion on the left and an unsorted portion on the right. On every pass, it scans the entire unsorted portion to find the minimum element, then swaps that minimum with the first element of the unsorted portion. After each pass, the sorted portion grows by one and the unsorted portion shrinks by one, until the entire array is sorted.
Unlike insertion sort, which builds the sorted portion by shifting elements into place, selection sort always completes a full scan before making any move. This is both its defining characteristic and the reason its time complexity is O(n²) in every case: best, average, and worst.
This applies to selection sort directly. The algorithm is not vague or approximate. It is precisely defined, finds the exact minimum on every pass, and makes exactly the right swap every time. Its limitations come not from imprecision but from the rigid structure that precision imposes.
The step-by-step process:
Here is how selection sort processes the array [19, 10, 4, 8, 3] pass by pass:
| Pass | Array State | Minimum Found | Swap |
| Initial | [19, 10, 4, 8, 3] | – | – |
| Pass 1 | [3, 10, 4, 8, 19] | 3 (index 4) | Swap 3 & 19 |
| Pass 2 | [3, 4, 10, 8, 19] | 4 (index 2) | Swap 4 & 10 |
| Pass 3 | [3, 4, 8, 10, 19] | 8 (index 3) | Swap 8 & 10 |
| Pass 4 | [3, 4, 8, 10, 19] | 10 (index 3) | Already in place. No swap needed |
The formal algorithm in numbered steps:
The language-agnostic pseudocode before diving into implementations:
for i from 0 to n - 2: min_index = i for j from i + 1 to n - 1: if arr[j] < arr[min_index]: min_index = j if min_index != i: swap arr[i] and arr[min_index]
The Python implementation scans for the minimum index in the inner loop and swaps only when necessary.
# Selection Sort - Python def selection_sort(arr): n = len(arr) for i in range(n - 1): min_index = i for j in range(i + 1, n): if arr[j] < arr[min_index]: min_index = j if min_index != i: arr[i], arr[min_index] = arr[min_index], arr[i] return arr # Example arr = [19, 10, 4, 8, 3] print(selection_sort(arr)) # Output: [3, 4, 8, 10, 19]
The Java version uses the same two-loop structure with a temporary variable for the swap.
// Selection Sort - Java public class SelectionSort { static void selectionSort(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; i++) { int minIndex = i; for (int j = i + 1; j < n; j++) { if (arr[j] < arr[minIndex]) minIndex = j; } if (minIndex != i) { int temp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = temp; } } } public static void main(String[] args) { int[] arr = {19, 10, 4, 8, 3}; selectionSort(arr); for (int val : arr) System.out.print(val + " "); // Output: 3 4 8 10 19 } }
The C++ implementation uses the same index-tracking approach, standard in competitive programming submissions.
// Selection Sort - C++ #include <iostream> using namespace std; void selectionSort(int arr[], int n) { for (int i = 0; i < n - 1; i++) { int minIndex = i; for (int j = i + 1; j < n; j++) { if (arr[j] < arr[minIndex]) minIndex = j; } if (minIndex != i) { int temp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = temp; } } } int main() { int arr[] = {19, 10, 4, 8, 3}; int n = sizeof(arr) / sizeof(arr[0]); selectionSort(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << " "; // Output: 3 4 8 10 19 return 0; }
The time and space complexity of selection sort across all cases:
| Case | Time Complexity | Why |
| Best Case | O(n2) | Even on a sorted array, the inner loop must scan the full unsorted portion on every pass to confirm the minimum |
| Average Case | O(n2) | Random input order changes nothing. The algorithm still performs (n-1) + (n-2) + … + 1 comparisons |
| Worst Case | O(n2) | Reverse-sorted input produces the same number of comparisons, n(n-1)/2, same as every other case |
| Space Complexity | O(1) | Sorting happens in-place using only a constant number of extra variables |
This is the most important thing to understand about selection sort, and the question interviewers ask most often about it. The reason all three cases are identical is structural: the algorithm has no way to skip the inner scan. To find the minimum of the unsorted portion, it must look at every element in that portion. There is no early exit condition. On pass 1 it does n-1 comparisons, on pass 2 it does n-2, and so on. Summing these gives n(n-1)/2 total comparisons, which is O(n²), regardless of whether the array is sorted, reversed, or random.
This is fundamentally different from insertion sort, which can exit its inner loop early when it finds an element smaller than the key. Selection sort has no equivalent shortcut. Finding a “minimum so far” is not the same as knowing you have found the minimum. You can only stop scanning once you have seen everything.
No. Standard selection sort is not stable. Stability means that equal elements retain their original relative order after sorting. Selection sort violates this because it swaps the minimum element directly into the front of the unsorted portion, and that swap can move a later-occurring equal element ahead of an earlier one.
For example, consider sorting [(3a), (3b), (1)] by value, where 3a appears before 3b originally. On pass 1, the minimum is 1, and it gets swapped with 3a, giving [(1), (3b), (3a)]. The relative order of 3a and 3b has been reversed. The algorithm is not stable.
A stable variant exists: instead of swapping, shift elements forward (like insertion sort does) to place the minimum in its correct position. This preserves relative order but adds more write operations.
Here is how selection sort compares to the two other foundational O(n²) sorting algorithms:
|
Algorithm |
Best Case | Average Case | Worst Case | Space | Stable? |
Key Trait |
| Selection Sort | O(n2) | O(n2) | O(n2) | O(1) | No | Fewest swaps: always exactly O(n) writes |
| Insertion Sort | O(n) | O(n2) | O(n2) | O(1) | Yes | Adaptive: O(n) on nearly sorted data |
| Bubble Sort | O(n) | O(n2) | O(n2) | O(1) | Yes | Simple but slowest in practice, with the most swaps |
Selection sort is the right tool for a narrow but real set of conditions: small arrays where minimising write operations matters more than minimising comparisons, and environments where predictable, input-independent performance is a constraint. For most other scenarios, insertion sort handles small data better and O(n log n) algorithms handle large data better. Understanding where selection sort fits, and where it does not, is exactly the depth of algorithmic reasoning that Interview Kickstart’s structured FAANG interview preparation program is built to develop.
Selection sort scans the full unsorted portion to find the minimum, then swaps it into place. It is not adaptive and always O(n²). Insertion sort takes the next element and shifts others to insert it correctly, it is adaptive and runs in O(n) on nearly sorted data.
Its O(n²) time complexity in all cases means it gains nothing even on nearly sorted data. Merge sort and quicksort run in O(n log n) and are dramatically faster on large inputs.
Yes. Instead of swapping the minimum to the front, shift elements forward to create a gap and insert the minimum there. This preserves relative order but adds more write operations per pass.
At most n-1 swaps for an array of n elements, one per pass, and only when the minimum is not already in its correct position. This is the lowest swap count of any simple sorting algorithm.
Generally yes. Selection sort makes far fewer writes, which matters in write-sensitive environments. Both are O(n²) and impractical for large data, but selection sort’s swap efficiency gives it a consistent edge in those niche use cases.
Recommended Reads:
Time Zone:
100% Free — No credit card needed.
Time Zone:
Master ML interviews with DSA, ML System Design, Supervised/Unsupervised Learning, DL, and FAANG-level interview prep.
Get strategies to ace TPM interviews with training in program planning, execution, reporting, and behavioral frameworks.
Course covering SQL, ETL pipelines, data modeling, scalable systems, and FAANG interview prep to land top DE roles.
Course covering Embedded C, microcontrollers, system design, and debugging to crack FAANG-level Embedded SWE interviews.
Nail FAANG+ Engineering Management interviews with focused training for leadership, Scalable System Design, and coding.
End-to-end prep program to master FAANG-level SQL, statistics, ML, A/B testing, DL, and FAANG-level DS interviews.
Learn to build AI agents to automate your repetitive workflows
Upskill yourself with AI and Machine learning skills
Prepare for the toughest interviews with FAANG+ mentorship
Time Zone:
Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills
25,000+ Professionals Trained
₹23 LPA Average Hike 60% Average Hike
600+ MAANG+ Instructors
Webinar Slot Blocked
Register for our webinar
Learn about hiring processes, interview strategies. Find the best course for you.
ⓘ Used to send reminder for webinar
Time Zone: Asia/Kolkata
Time Zone: Asia/Kolkata
Hands-on AI/ML learning + interview prep to help you win
Explore your personalized path to AI/ML/Gen AI success
The 11 Neural “Power Patterns” For Solving Any FAANG Interview Problem 12.5X Faster Than 99.8% OF Applicants
The 2 “Magic Questions” That Reveal Whether You’re Good Enough To Receive A Lucrative Big Tech Offer
The “Instant Income Multiplier” That 2-3X’s Your Current Tech Salary
Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills
Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills
Webinar Slot Blocked
Time Zone: Asia/Kolkata
Hands-on AI/ML learning + interview prep to help you win
Time Zone: Asia/Kolkata
Hands-on AI/ML learning + interview prep to help you win
Explore your personalized path to AI/ML/Gen AI success
See you there!