Python implementation of the Selection Sort algorithm
Data Structure Sorting (Article) Sorting (Program)
20
Given Input:
Original array: [64, 25, 12, 22, 11]
Expected Output:
Sorted array: [11, 12, 22, 25, 64]
Program:
# 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)
Output:
Original array: [64, 25, 12, 22, 11]
Sorted array: [11, 12, 22, 25, 64]
Explanation:
- Outer Loop: Iterates over each element in the array.
- Inner Loop: Finds the minimum element from the unsorted part of the array.
- Swap: Swaps the minimum element with the first unsorted element.
- Sorted Output: After the loops complete, the array is sorted in ascending order.
This Particular section is dedicated to Programs only. If you want learn more about Data Structure. Then you can visit below links to get more depth on this subject.
Sorted array: [11, 12, 22, 25, 64]
Program:
# 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)
Output:
Original array: [64, 25, 12, 22, 11] Sorted array: [11, 12, 22, 25, 64]
Explanation:
- Outer Loop: Iterates over each element in the array.
- Inner Loop: Finds the minimum element from the unsorted part of the array.
- Swap: Swaps the minimum element with the first unsorted element.
- Sorted Output: After the loops complete, the array is sorted in ascending order.
This Particular section is dedicated to Programs only. If you want learn more about Data Structure. Then you can visit below links to get more depth on this subject.