Selection Sort Explained: Algorithm & Python Example

Learn Selection Sort, a simple, in-place sorting algorithm perfect for beginners. Understand its mechanics and get a Python implementation for efficient array manipulation.

9.7 Selection Sort

Selection Sort is a simple, in-place comparison-based sorting algorithm. It's an excellent choice for beginners to grasp the fundamentals of sorting and array manipulation. While not the most efficient for large datasets, its straightforwardness makes it valuable for educational purposes and sorting smaller lists.

What is Selection Sort?

Selection Sort works by dividing the input list into two parts: a sorted subarray and an unsorted subarray. In each iteration, it finds the minimum element from the unsorted subarray and swaps it with the first element of the unsorted subarray. This process gradually expands the sorted subarray until the entire list is sorted.

Time and Space Complexity

MetricComplexity
Time (Best)O(n²)
Time (Average)O(n²)
Time (Worst)O(n²)
SpaceO(1)
  • Space Complexity: O(1) - This indicates it's an in-place sorting algorithm, meaning it sorts the array without requiring significant additional memory.
  • Stability: Not stable - The relative order of equal elements is not preserved.
  • In-place: Yes

Key Characteristics of Selection Sort

  • Simplicity: Easy to understand and implement.
  • In-place: Requires minimal extra memory.
  • Not Stable: The order of equal elements might change.
  • Inefficiency for Large Lists: Its quadratic time complexity (O(n²)) makes it slow for large datasets.

Selection Sort Algorithm Steps

  1. Initialization: Start from the first element of the array. Consider this element as the minimum.
  2. Find Minimum: Traverse the remaining unsorted portion of the array to find the actual minimum element.
  3. Swap: Swap the found minimum element with the current element (the one you initially assumed to be the minimum).
  4. Advance: Move to the next element in the array and repeat steps 2 and 3.
  5. Completion: Continue this process until the entire array is sorted.

Python Implementation of Selection Sort

def selection_sort(arr):
    """
    Sorts an array using the Selection Sort algorithm.

    Args:
        arr: A list of comparable elements.
    """
    n = len(arr)
    # Traverse through all array elements
    for i in range(n):
        # Find the minimum element in the remaining unsorted array
        min_index = i
        for j in range(i + 1, n):
            if arr[j] < arr[min_index]:
                min_index = j

        # Swap the found minimum element with the first element of the unsorted part
        if min_index != i:
            arr[i], arr[min_index] = arr[min_index], arr[i]

Example Usage

data = [64, 25, 12, 22, 11]
selection_sort(data)
print("Sorted array:", data)

Output:

Sorted array: [11, 12, 22, 25, 64]

How Selection Sort Works: Step-by-Step

Let's trace the sorting of [64, 25, 12, 22, 11]:

Initial Array: [64, 25, 12, 22, 11]

  • Pass 1:

    • The smallest element in the unsorted part ([64, 25, 12, 22, 11]) is 11.
    • Swap 11 with the first element 64.
    • Result: [11, 25, 12, 22, 64] (Sorted part: [11])
  • Pass 2:

    • Consider the unsorted part: [25, 12, 22, 64].
    • The smallest element is 12.
    • Swap 12 with the first element of the unsorted part (25).
    • Result: [11, 12, 25, 22, 64] (Sorted part: [11, 12])
  • Pass 3:

    • Consider the unsorted part: [25, 22, 64].
    • The smallest element is 22.
    • Swap 22 with the first element of the unsorted part (25).
    • Result: [11, 12, 22, 25, 64] (Sorted part: [11, 12, 22])
  • Pass 4:

    • Consider the unsorted part: [25, 64].
    • The smallest element is 25. It's already in the correct position.
    • No swap needed.
    • Result: [11, 12, 22, 25, 64] (Sorted part: [11, 12, 22, 25])
  • Pass 5:

    • Consider the unsorted part: [64].
    • The smallest element is 64. It's already in the correct position.
    • No swap needed.
    • Result: [11, 12, 22, 25, 64] (Sorted part: [11, 12, 22, 25, 64])

The array is now fully sorted.

When to Use Selection Sort

Selection Sort is best suited for:

  • Educational Purposes: Its simplicity makes it an ideal algorithm for teaching fundamental sorting concepts.
  • Small Datasets: It performs adequately for lists with a small number of elements where performance is not a critical concern.
  • Memory-Constrained Environments: Its O(1) space complexity is advantageous when memory usage must be minimized.
  • Minimizing Swaps: If the cost of swapping elements is high, Selection Sort might be preferable as it performs at most n-1 swaps.

Selection Sort vs. Other Sorting Algorithms

FeatureSelection SortMerge SortQuick Sort
Time (Best)O(n²)O(n log n)O(n log n)
Time (Avg)O(n²)O(n log n)O(n log n)
Time (Worst)O(n²)O(n log n)O(n²)
SpaceO(1)O(n)O(log n)
StabilityNoYesNo
In-placeYesNoYes
Practical UseRareCommonVery Common

Conclusion

Although Selection Sort is not the most efficient algorithm for large datasets due to its quadratic time complexity, it serves as an excellent pedagogical tool for understanding sorting principles. Its in-place nature and low memory footprint make it a reasonable choice for applications with limited memory and small data volumes.

SEO Keywords

  • Selection Sort Python
  • In-place sorting algorithm
  • Simple sort algorithm Python
  • Python Selection Sort code
  • Basic sorting techniques
  • Selection Sort example
  • Comparison based sorting Python
  • Sort small lists Python
  • Python sort tutorial
  • Sorting algorithm for beginners

Interview Questions

  • What is Selection Sort and how does it work?
  • What are the time and space complexities of Selection Sort?
  • Is Selection Sort a stable algorithm? Why or why not?
  • Compare Selection Sort with Bubble Sort and Insertion Sort.
  • In what scenarios would you use Selection Sort?
  • How does Selection Sort differ from Merge Sort and Quick Sort?
  • Write a Python implementation of Selection Sort and explain it.
  • Why is Selection Sort considered inefficient for large datasets?
  • Can Selection Sort be modified to be stable? If so, how?
  • What is the advantage of Selection Sort in memory-constrained systems?