Original array: [64, 25, 12, 22, 11]
Sorted array: [11, 12, 22, 25, 64]
# Selection Sort in Python
def selection_sort(arr):
# Traverse through all array elements
for i in range(len(arr)):
# Find the minimum element in the unsorted portion of the array
min_idx = i
for j in range(i+1, len(arr)):
if arr[j] < arr[min_idx]:
min_idx = j
# Swap the found minimum element with the first element of the unsorted portion
arr[i], arr[min_idx] = arr[min_idx], arr[i]
# Example usage
arr = [64, 25, 12, 22, 11]
print("Original array:", arr)
selection_sort(arr)
print("Sorted array:", arr)
Original array: [64, 25, 12, 22, 11]
Sorted array: [11, 12, 22, 25, 64]
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.