What is selection sort? Time complexity?

Understanding Selection Sort: A Simple Guide to Sorting Algorithms

Ever tried arranging a deck of cards? That's similar to what sorting algorithms do with data! Today, we'll explore one of the simplest sorting algorithms: Selection Sort.

What is Selection Sort?

Selection sort is a straightforward algorithm that sorts an array (list of items) by repeatedly finding the minimum element from the unsorted part and placing it at the beginning.

Let's illustrate with an example: [64, 25, 12, 22, 11].

1. Find the smallest element (11). Swap it with the first element (64).

2. Now consider the remaining unsorted portion [64, 25, 12, 22]. Find the smallest again(12), swap with 64.

3. Repeat until everything's sorted.

How Selection Sort Works: Step-by-Step

Selection sort follows these steps:

  1. Find the minimum: Search through the unsorted part of the array to find the smallest element.
  2. Swap: Exchange the minimum element with the first element of the unsorted part.
  3. Repeat: Repeat steps 1 & 2 for the remaining unsorted part until the entire array is sorted.

Here's a simple pseudocode:

for i from 0 to n-1: min = i for j from i+1 to n: if arr[j] < arr[min]: min = j swap arr[i] and arr[min]

Time Complexity

Selection sort has a time complexity of O(n^2) in all cases (best, average, and worst). This means the time it takes increases quadratically with the size of the input. It's not the fastest for large datasets.

Its space complexity is O(1), meaning it uses constant extra space, making it quite memory efficient.

Advantages and Disadvantages

Advantages:

  • Simple to understand and implement.
  • Efficient for small datasets or where memory is a constraint.

Disadvantages:

  • Inefficient for large datasets due to O(n^2) time complexity.
  • Slower than algorithms like merge sort or quicksort for larger inputs.

Selection Sort in Python


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

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

Conclusion

Selection sort is a basic yet valuable sorting algorithm. Its simplicity makes it a good starting point for learning about sorting. While not the most efficient for large datasets, it's a great example of an in-place algorithm with low space complexity. Consider using it for smaller datasets or educational purposes.