Selection Sort Algorithm

Last updated by Dipen Dadhaniya on Apr 29, 2026 at 04:22 PM

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.

| Reading Time: 3 minutes

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.

Key Takeaways

  • All three complexity cases are O(n²), and that is by design. Selection sort must always scan the full unsorted portion to confirm the minimum. There is no early exit. This structural constraint makes it the only common sorting algorithm with no adaptive behaviour whatsoever.
  • Selection sort makes the fewest writes of any simple sorting algorithm. At most n-1 swaps, regardless of input. In scenarios where write operations are expensive, flash memory, EEPROMs, this is a genuine practical advantage.
  • Standard selection sort is not stable. The long-distance swap can reorder equal elements. Knowing this, and knowing that a stable variant exists (shift instead of swap), is what separates complete interview answers from incomplete ones.
  • The dry run observation that wins interviews: selection sort always makes exactly n-1 passes and scans (n-i) elements on pass i. Being able to narrate this while tracing the array, not just writing the output, is the mark of a prepared candidate.
  • Insertion sort is almost always preferable for small arrays. It is adaptive, stable, and faster in practice on nearly sorted data. Selection sort’s only genuine edge is its minimum write count, outside that scenario, insertion sort wins.

What Is Selection 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.

“The purpose of abstracting is not to be vague, but to create a new semantic level in which one can be absolutely precise.” – Edsger W. Dijkstra

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.

How Selection Sort Works

The step-by-step process:

  1. Start with the full array as the unsorted portion.
  2. Scan the entire unsorted portion to find the index of the minimum element.
  3. Swap the minimum element with the first element of the unsorted portion.
  4. Move the boundary one position to the right. The sorted portion now includes one more element.
  5. Repeat from step 2 until the unsorted portion has only one element left.
💡 Pro Tip: Notice that selection sort always completes a full scan of the unsorted portion before making any swap. There is no shortcut. Even if the array is already sorted, it still scans everything. This is exactly why all three complexity cases are O(n²), and it is one of the most important things to understand before your interview.

Step-by-Step Dry Run: Array [19, 10, 4, 8, 3]

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
🏆 Interview Callout: The key observation when tracing selection sort is that it always makes exactly n-1 swaps for an array of n elements, regardless of the input. Even if no swap is needed on a given pass (as in Pass 4 above), the algorithm still completes a full scan. Being able to point this out clearly during a trace is what separates strong interview answers from average ones.

Selection Sort Algorithm

The formal algorithm in numbered steps:

  1. Set the outer loop index i from 0 to n-2 (the last element falls into place automatically).
  2. Assume the current position i holds the minimum. Set min_index = i.
  3. Scan from i+1 to n-1. If any element is smaller than arr[min_index], update min_index.
  4. After the full scan, if min_index != i, swap arr[min_index] with arr[i].
  5. Increment i and repeat from step 2.

Selection Sort Pseudocode

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]

Selection Sort Code

Selection Sort in Python

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]
💡 Pro Tip: The if min_index != i check before the swap is worth noting in an interview. It avoids a needless swap when the minimum is already in the correct position, reducing the total number of write operations. On an already-sorted array this means zero swaps happen, even though the algorithm still performs all O(n²) comparisons.

Selection Sort in Java

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
    }
}

Selection Sort in C++

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;
}
💡 Pro Tip: When writing selection sort in an interview, always track the index of the minimum rather than the minimum value itself. Tracking the index lets you perform the swap directly. Tracking the value requires a second pass to find where it lives, an unnecessary complication that signals imprecise thinking.

Selection Sort Time and Space Complexity

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

Why are all three cases O(n²)

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.

🏆 Interview Callout: Selection sort is the only common sorting algorithm where best, average, and worst case are all O(n²). When an interviewer asks why, the answer is: it must always scan the entire remaining unsorted portion to confirm the minimum, there is no way to short-circuit the inner loop. That single sentence demonstrates genuine understanding of the algorithm, not just memorised complexity values.

Is Selection Sort Stable?

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.

Selection Sort vs Insertion Sort vs Bubble Sort

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

When to Use Selection Sort

Use selection sort when:

  • Write operations are expensive. Selection sort makes at most n-1 swaps, fewer than any other simple sorting algorithm.
  • The array is small. Its O(n²) cost is acceptable for datasets under 20 to 30 elements where overhead of complex algorithms is not justified.
  • Memory is extremely constrained. O(1) space with minimal write overhead is hard to beat in embedded or low-resource environments.
  • Simplicity of implementation matters more than speed. The two-loop structure is straightforward to write and debug correctly.

Avoid selection sort when:

  • The dataset is large. O(n²) in all cases makes it impractical for thousands of elements or more.
  • The data is nearly sorted. Selection sort offers no benefit on nearly sorted input, unlike insertion sort which runs in O(n).
  • Stability is required. The swap-based approach disrupts the relative order of equal elements.
  • You need guaranteed O(n log n) performance. Use merge sort or heapsort instead.
“If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.” – David Leinweber

Advantages and Disadvantages of Selection Sort

Advantages

  • Minimum number of swaps: at most n-1, regardless of input order.
  • Simple to implement. The two-loop structure is easy to write correctly from scratch.
  • In-place. Requires only O(1) extra memory.
  • Predictable performance. The same number of comparisons every time, which simplifies performance analysis in constrained systems.

Disadvantages

  • O(n²) in all cases with no adaptive behaviour, even on nearly sorted or already sorted input.
  • Not stable. Long-distance swaps can disrupt the relative order of equal elements.
  • Outperformed by insertion sort in almost every practical scenario involving small or nearly sorted arrays.
  • Completely impractical for large datasets. Merge sort and quicksort are orders of magnitude faster.

Conclusion

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.

FAQs: Selection Sort

Q1. What is the difference between selection sort and insertion sort?

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.

Q2. Why is selection sort not used in practice for large datasets?

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.

Q3. Can selection sort be made stable?

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.

Q4. How many swaps does selection sort make?

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.

Q5. Is selection sort better than bubble sort?

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.

References

  1. Insertion Sort vs. Selection Sort

Recommended Reads:

Last updated on: April 29, 2026
Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Strange Tier-1 Neural “Power Patterns” Used By 20,013 FAANG Engineers To Ace Big Tech Interviews

100% Free — No credit card needed.

Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

IK courses Recommended

Master ML interviews with DSA, ML System Design, Supervised/Unsupervised Learning, DL, and FAANG-level interview prep.

Fast filling course!

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.

Select a course based on your goals

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

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Almost there...
Share your details for a personalised FAANG career consultation!
Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!

Registration completed!

🗓️ Friday, 18th April, 6 PM

Your Webinar slot

Mornings, 8-10 AM

Our Program Advisor will call you at this time

Register for our webinar

Transform Your Tech Career with AI Excellence

Transform Your Tech Career with AI Excellence

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

Interview Kickstart Logo

Register for our webinar

Transform your tech career

Transform your tech career

Learn about hiring processes, interview strategies. Find the best course for you.

Loading_icon
Loading...
*Invalid Phone Number

Used to send reminder for webinar

By sharing your contact details, you agree to our privacy policy.
Choose a slot

Time Zone: Asia/Kolkata

Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Switch to ML: Become an ML-powered Tech Pro

Explore your personalized path to AI/ML/Gen AI success

Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!
Registration completed!
🗓️ Friday, 18th April, 6 PM
Your Webinar slot
Mornings, 8-10 AM
Our Program Advisor will call you at this time

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Your PDF Is One Step Away!

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

Transform Your Tech Career with AI Excellence

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

Loading_icon
Loading...
*Invalid Phone Number
By sharing your contact details, you agree to our privacy policy.
Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Switch to ML: Become an ML-powered Tech Pro

Explore your personalized path to AI/ML/Gen AI success

Registration completed!

See you there!

Webinar on Friday, 18th April | 6 PM
Webinar details have been sent to your email
Mornings, 8-10 AM
Our Program Advisor will call you at this time