Selection Sort Algorithm: Step-by-Step Guide


5 min read 07-11-2024
Selection Sort Algorithm: Step-by-Step Guide

Understanding the Selection Sort Algorithm

The selection sort algorithm is a simple sorting algorithm that works by repeatedly selecting the minimum element from the unsorted subarray and placing it at the beginning. It's a relatively easy sorting algorithm to understand and implement, making it a great starting point for learning about sorting algorithms.

Let's visualize selection sort using a simple analogy. Imagine you have a box filled with unsorted socks. Your goal is to arrange them in order of size, starting with the smallest sock. You would first find the smallest sock in the box, take it out, and place it in a separate pile. You would then repeat this process for the remaining socks in the box, finding the smallest remaining sock each time and placing it in your new pile. This process continues until all socks are sorted into a neat pile based on size.

Similarly, in the selection sort algorithm, we continuously scan the unsorted subarray to identify the smallest element and place it at the beginning of the array. This process effectively builds a sorted subarray, while the unsorted subarray shrinks with each iteration.

Step-by-Step Guide to Selection Sort

Here's a breakdown of the selection sort algorithm, step-by-step:

  1. Initialization: Begin by selecting the first element of the array as the minimum element.

  2. Iteration: Iterate through the remaining unsorted elements in the array, comparing each element with the current minimum element.

  3. Minimum Element Identification: If a smaller element is found, update the minimum element to the newly found smaller element.

  4. Swapping: After iterating through all elements in the unsorted subarray, swap the current minimum element with the element at the beginning of the unsorted subarray.

  5. Sorted Subarray Expansion: The first element is now sorted. Move to the next element in the array and repeat steps 2-4 for the remaining unsorted subarray.

  6. Termination: Repeat steps 2-5 until the entire array is sorted.

Example: Sorting an Array Using Selection Sort

Let's illustrate the selection sort algorithm with a simple example:

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

Iteration 1:

  • Minimum Element: 11
  • Swap: Swap 64 with 11, resulting in the array: [11, 25, 12, 22, 64]
  • Sorted Subarray: [11]

Iteration 2:

  • Minimum Element: 12
  • Swap: Swap 25 with 12, resulting in the array: [11, 12, 25, 22, 64]
  • Sorted Subarray: [11, 12]

Iteration 3:

  • Minimum Element: 22
  • Swap: Swap 25 with 22, resulting in the array: [11, 12, 22, 25, 64]
  • Sorted Subarray: [11, 12, 22]

Iteration 4:

  • Minimum Element: 25
  • Swap: No swap needed, as 25 is already in the correct position.
  • Sorted Subarray: [11, 12, 22, 25]

Iteration 5:

  • Minimum Element: 64
  • Swap: No swap needed, as 64 is already in the correct position.
  • Sorted Subarray: [11, 12, 22, 25, 64]

Final Sorted Array: [11, 12, 22, 25, 64]

Visual Representation of Selection Sort

To further clarify the process, let's represent the selection sort algorithm visually using a simple diagram:

Unsorted Array Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5 Sorted Array
[64, 25, 12, 22, 11] [11, 25, 12, 22, 64] [11, 12, 25, 22, 64] [11, 12, 22, 25, 64] [11, 12, 22, 25, 64] [11, 12, 22, 25, 64] [11, 12, 22, 25, 64]

Implementation of Selection Sort in Python

Let's now translate the selection sort algorithm into Python code.

def selection_sort(array):
  """
  Performs selection sort on the given array.

  Args:
    array: The array to be sorted.

  Returns:
    The sorted array.
  """
  n = len(array)
  for i in range(n):
    min_index = i
    for j in range(i + 1, n):
      if array[min_index] > array[j]:
        min_index = j
    array[i], array[min_index] = array[min_index], array[i]
  return array

# Example usage:
unsorted_array = [64, 25, 12, 22, 11]
sorted_array = selection_sort(unsorted_array)
print(sorted_array) # Output: [11, 12, 22, 25, 64]

Time Complexity and Space Complexity of Selection Sort

Time Complexity:

Selection sort has a time complexity of O(n^2), where n is the number of elements in the array. This means the execution time grows quadratically with the size of the input array.

Space Complexity:

Selection sort has a space complexity of O(1), meaning it requires constant additional memory regardless of the input array size.

Advantages and Disadvantages of Selection Sort

Advantages:

  • Simple Implementation: Selection sort is very easy to understand and implement.
  • In-Place Sorting: Selection sort performs sorting in-place, meaning it modifies the original array directly, without requiring additional memory.

Disadvantages:

  • Inefficient for Large Datasets: Selection sort's time complexity of O(n^2) makes it inefficient for large datasets.
  • Not Adaptive: Selection sort doesn't adapt to partially sorted arrays, making it equally inefficient for already sorted arrays.

Use Cases of Selection Sort

Although selection sort is not the most efficient sorting algorithm for large datasets, it finds its applications in specific scenarios:

  • Small Datasets: For small arrays, selection sort's simplicity and in-place nature make it a viable choice.
  • Educational Purposes: Selection sort serves as a foundational sorting algorithm for learning about sorting concepts.

FAQs

1. Is selection sort stable?

No, selection sort is not a stable sorting algorithm. This means that elements with the same value might not maintain their relative order after sorting. For example, if you have two elements with the same value, one appearing before the other in the original array, selection sort might not preserve this order after sorting.

2. What are the differences between selection sort and bubble sort?

Both selection sort and bubble sort are simple sorting algorithms with a time complexity of O(n^2). However, they differ in their approach to finding and swapping elements:

  • Selection Sort: Finds the minimum element in the unsorted subarray and swaps it with the element at the beginning of the subarray.
  • Bubble Sort: Compares adjacent elements and swaps them if they are in the wrong order, effectively "bubbling" the largest element to the end of the array.

3. Is selection sort a good choice for sorting large datasets?

Selection sort is not a good choice for sorting large datasets due to its O(n^2) time complexity. For large datasets, other more efficient sorting algorithms like Merge Sort or Quick Sort are preferred.

4. What are the applications of selection sort in real-world scenarios?

While selection sort is not ideal for large datasets, it finds its applications in specific scenarios, such as sorting small datasets, educational purposes, and in situations where memory usage is a constraint.

5. What is the best-case time complexity of selection sort?

Even in the best-case scenario, where the array is already sorted, selection sort still needs to perform n-1 comparisons for each element, resulting in a time complexity of O(n^2).

Conclusion

The selection sort algorithm is a simple and intuitive sorting algorithm that repeatedly selects the minimum element from the unsorted subarray and places it at the beginning. It's an excellent choice for learning about sorting algorithms and is practical for sorting small datasets. However, its O(n^2) time complexity makes it less efficient for large datasets compared to other more sophisticated sorting algorithms.