Selection Sort
Anjana Silva
Team Lead ?? | Sharing insights on software engineering for your growth ?? Be sure to follow my profile ?? | Cricket enthusiast ??
Selection sort is a simple sorting algorithm that divides the input list into two parts: a sorted sublist and an unsorted sublist. Initially, the sorted sublist is empty, and the unsorted sublist contains all elements. The algorithm repeatedly finds the minimum element from the unsorted sublist and moves it to the beginning of the sorted sublist. This process is repeated until the unsorted sublist becomes empty.
When to use selection sort
? Selection sort is efficient for small datasets or when memory space is limited.
? It has a simple implementation and is easy to understand.
领英推荐
When not to use selection sort
? Selection sort has a time complexity of O(n^2), making it inefficient for large datasets. For large datasets, other more efficient sorting algorithms like quicksort, mergesort, or heapsort should be used.
? It is not suitable for datasets with a large number of elements or when a faster sorting algorithm is required.
A simple selection sort example in Python,
def selection_sort(arr):
# Traverse through all array elements
for i in range(len(arr)):
# Find the minimum element in the remaining unsorted array
min_index = i
for j in range(i+1, len(arr)):
if arr[j] < arr[min_index]:
min_index = j
# Swap the found minimum element with the first element
arr[i], arr[min_index] = arr[min_index], arr[i]
# Example usage:
arr = [64, 34, 25, 12, 22, 11, 90]
selection_sort(arr)
print("Sorted array is:", arr)
I hope you enjoyed this post. Thank you.