Understanding Selection Sort in Python

Introduction

Sorting is a fundamental operation in computer science and plays a crucial role in various applications. Python, being a versatile programming language, offers several sorting algorithms to organize data efficiently. One such algorithm is the Selection Sort, which though not the most efficient, is relatively easy to understand and implement. In this article, we will explore the concepts behind Selection Sort and provide a Python implementation to illustrate its functionality.

Overview Selection Sort

Selection Sort is an in-place comparison-based sorting algorithm. It works by dividing the input array into two parts: a sorted portion and an unsorted portion. The algorithm repeatedly selects the minimum (or maximum) element from the unsorted portion and swaps it with the first element of the unsorted portion. This process continues until the entire array becomes sorted.

Visual Representation of Selection Sort

The following steps will assist you in grasping the workings of selection sort by providing an example with an array.

Iteration 1

The positions of the data in the array after the initial iteration, using the selection sort algorithm.

Iteration 2

The positions of the data in the array after the second iteration, using the selection sort algorithm.

Iteration 3

The positions of the data in the array after the third iteration, using the selection sort algorithm.

Iteration 4

The positions of the data in the array after the final iteration (or the sorted array), using the selection sort algorithm.

Step-by-Step Implementation in Python

Let’s walk through the step-by-step implementation of the Selection Sort algorithm in Python:


def selection_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        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]

Explanation:

1. The function `selection_sort` takes an array `arr` as input.

2. The variable `n` stores the length of the array.

3. We iterate over the array using the outer loop `for i in range(n – 1)`. This loop represents the sorted portion of the array. We stop at `n – 1` because the last element will automatically be in the correct position after all other elements have been sorted.

4. Inside the outer loop, we initialize `min_idx` to `i`, which represents the index of the minimum element in the unsorted portion.

5. The inner loop `for j in range(i + 1, n)` iterates over the unsorted portion of the array. It compares each element with the current minimum element (`arr[min_idx]`).

6. If a smaller element is found, we update `min_idx` to the index of that element.

7. After the inner loop completes, we swap the element at index `i` with the minimum element found in step 6, using a Pythonic swap operation (`arr[i], arr[min_idx] = arr[min_idx], arr[i]`).

8. The process continues until the outer loop completes, resulting in a sorted array.

Example Usage:


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

Now, let’s see the Selection Sort algorithm in action with an example:

Output


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

Complexity Analysis of Selection Sort

Time Complexity

The time complexity of Selection Sort can be analyzed as follows:

  • In the worst-case scenario, Selection Sort performs a comparison for each element in the array for each pass of the outer loop. The outer loop iterates n-1 times, where n is the number of elements in the array.
  • In the inner loop, the number of comparisons decreases by one with each iteration of the outer loop, as the sorted portion of the array grows. Therefore, the number of comparisons in the inner loop can be approximated to (n-1) + (n-2) + … + 1, which is equal to (n*(n-1))/2.
  • Overall, the time complexity of Selection Sort is O(n^2), which signifies a quadratic time complexity.

Space Complexity

The space complexity of Selection Sort refers to the additional space used by the algorithm, apart from the input array.

  • Selection Sort operates in-place, meaning it does not require additional space proportional to the size of the input array.
  • The space complexity of Selection Sort is O(1), as the algorithm only requires a constant amount of extra space to perform the swapping operations.

Key Takeaways

1. The time complexity of Selection Sort is O(n^2), where n represents the number of elements in the array.

2. The space complexity of Selection Sort is O(1), as it operates in-place and requires only a constant amount of additional space.

3. Selection Sort is not the most efficient sorting algorithm, especially for large datasets. Its time complexity makes it less favorable compared to other sorting algorithms like Merge Sort or Quick Sort.

4. However, Selection Sort can still be useful for small input sizes or in situations where simplicity and ease of implementation are prioritized over efficiency.

Understanding the time and space complexity of sorting algorithms is essential for selecting the most appropriate algorithm for specific use cases and optimizing performance in software development.

Conclusion

Selection Sort is a simple yet straightforward sorting algorithm that can be easily implemented in Python. While it may not be the most efficient algorithm for large datasets, it is a valuable learning tool for understanding sorting principles. By following the step-by-step implementation outlined in this article, you should now have a clear understanding of how Selection Sort works and how to apply it in your Python projects.

Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! I’m Subhankar Rakshit, the brains behind PySeek. I’m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles: 194