Data Structures and Algorithms: How to Sort a List Using Selection Sort in Python

python 301 Algorithms selection sort

Selection sort is a sorting algorithm that works by finding the smallest element in the unsorted part of a list and swapping it with the first element of that part. It repeats this process until the whole list is sorted. Selection sort is easy to implement and understand, but it is not very efficient or fast. It has a time complexity of O(n^2), which means that it takes quadratic time to sort a list of n elements.

a selection sort example:

def selection_sort(corgi_age_list):
    n = len(corgi_age_list)

    for i in range(n):    # Traverse through all array
        min_index = i
        for j in range(i + 1, n): # Find the minimum element
            if corgi_age_list[j] < corgi_age_list[min_index]:
                min_index = j

        corgi_age_list[i], corgi_age_list[min_index] = corgi_age_list[min_index], corgi_age_list[i] # Swap element with the first element

# Example usage:
my_corgi_age_list = [14, 4, 5, 12, 9, 11, 18]
print("Original List:", my_corgi_age_list) # Original List: [14, 4, 5, 12, 9, 11, 18]

selection_sort(my_corgi_age_list)

print("Sorted List:", my_corgi_age_list) # Sorted List: [4, 5, 9, 11,  12, 14, 18]

In this example, the selection_sort function takes an array as input and sorts it in ascending order. The algorithm iterates through the array, finding the minimum element in each iteration and swapping it with the first element of the unsorted portion. This process is repeated until the entire array is sorted.

This demonstrates the basic concept of Selection Sort. The algorithm repeatedly selects the minimum element from the unsorted part of the array and swaps it with the first unsorted element, effectively growing the sorted part of the array. Note that Selection Sort is not the most efficient sorting algorithm, especially for large datasets, but it serves as a good educational example due to its simplicity.

Here are some of the key points to remember about Selection Sort:

  • It is a simple algorithm that is easy to understand and implement.
  • It is efficient for small datasets but inefficient for large datasets.
  • It has a time complexity of O(n^2), where n is the length of the array.
  • It is an in-place sorting algorithm, meaning that it does not require additional memory space.

Quiz

Related posts

Leave a Comment