Selection Sort in Python: A Comprehensive Guide
1. What is Selection Sort?
Selection sort is a simple comparison-based sorting technique. The main idea behind the algorithm is to keep selecting the smallest (or largest, depending on the sorting order) element from the unsorted section of the list and swapping it with the first unsorted element. This process is repeated until the entire list is sorted.
2. How Does Selection Sort Work?
Imagine you're looking through a deck of cards. With selection sort, you'd:
- Look for the smallest card.
- Swap it with the first card.
- Look for the smallest card from the remaining deck.
- Swap it with the second card.
- Repeat this process until the entire deck is sorted.
2.1. Pseudocode for Selection Sort
Below is the pseudocode for selection sort:
for i from 0 to n-1
min_index = i
for j from i+1 to n
if array[j] < array[min_index]
min_index = j
if min_index != i
swap(array[i], array[min_index])
3. Python Implementation of Selection Sort
Let's delve into the Python code to see the magic of selection sort in action:
def selection_sort(arr):
for i in range(len(arr)):
min_index = i
for j in range(i+1, len(arr)):
if arr[j] < arr[min_index]:
min_index = j
# Swap the minimum value found with the first value
arr[i], arr[min_index] = arr[min_index], arr[i]
return arr
# Sample usage
arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = selection_sort(arr)
print("Sorted array is:", sorted_arr)
When you run this code, you should see the output:
Sorted array is: [11, 12, 22, 25, 34, 64, 90]
4. Time Complexity
It's essential to understand the performance implications of using selection sort. For every item in the list, the algorithm needs to find the minimum from the unsorted portion. This results in a time complexity of O(n^2). Due to its quadratic time complexity, selection sort isn't efficient on larger lists. For small lists or lists where simplicity of code is a priority, however, it's a suitable option.
5. Conclusion
Selection sort is one of the fundamental sorting algorithms that every budding programmer should be acquainted with. While it might not be the most efficient, its ease of understanding and implementation make it a valuable tool in the programmer's toolkit. Whether you're just starting out or brushing up on the basics, understanding selection sort will give you a deeper appreciation for more advanced sorting methods.