There are no items in your cart
Add More
Add More
Item Details | Price |
---|
Welcome to NERCHUKO! Today, we're diving into Selection Sort - imagine you're sorting a deck of cards by repeatedly finding the smallest card and moving it to the front. That's exactly how Selection Sort works!
Sun Jan 5, 2025
Think of Selection Sort like organizing your playing cards: you scan through all cards to find the smallest one, put it first, then repeat with the remaining cards. It's called "Selection" Sort because you're literally selecting the smallest element each time!
Imagine organizing books on a shelf by height:
Let's sort this list: [64, 25, 12, 22, 11]
Step 1: Find smallest (11)
[64, 25, 12, 22, 11] → [11, 25, 12, 22, 64]
Step 2: Find next smallest (12)
[11, 25, 12, 22, 64] → [11, 12, 25, 22, 64]
Step 3: Find next smallest (22)
[11, 12, 25, 22, 64] → [11, 12, 22, 25, 64]
Step 4: Compare remaining
[11, 12, 22, 25, 64] (Already in order!)
Get a visual explanation of Selection Sort in action:
def selection_sort(arr):
# Get the length of the array
n = len(arr)
# Iterate through the array
for i in range(n):
# Assume the current position has the minimum value
min_idx = i
# Look through the rest of the array for a smaller element
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
min_idx = j
# Swap the found minimum element with the first element
arr[i], arr[min_idx] = arr[min_idx], arr[i]
# Print each step (optional, for understanding)
print(f"Step {i + 1}: {arr}")
return arr
# Example usage
numbers = [64, 25, 12, 22, 11]
print("Original array:", numbers)
sorted_numbers = selection_sort(numbers.copy())
print("Sorted array:", sorted_numbers)
Best Case: O(n²) - Even if the array is sorted
Average Case: O(n²) - For typical random data
Worst Case: O(n²) - When array is reverse sorted
In simple terms: For 100 items, it always needs about 10,000 steps!
Try sorting this array by hand: [31, 15, 7, 28, 19]
Keep learning with NERCHUKO! 🚀