Selection Sort in Python

0

Selection Sort in Python

Now that we understand the logic behind Selection Sort, let’s write the code to implement it.

We’ll use the same example list:

my_list = [2, 6, 5, 1, 3, 4]

Step 1: Define the Function

We’ll create a function called selection_sort that takes a list as input:

def selection_sort(my_list):
    # Loop through each index except the last one
    for i in range(len(my_list) – 1):
        # Set the current index as the minimum
        min_index = i
        # Loop through the rest of the list to find the actual minimum
        for j in range(i + 1, len(my_list)):
            if my_list[j] < my_list[min_index]:
                min_index = j
        # Swap the values if the minimum is not already at position i
        if i != min_index:
            temp = my_list[i]
            my_list[i] = my_list[min_index]
            my_list[min_index] = temp
    return my_list

Step 2: How the Code Works

  1. Outer loop (i): Goes through the list from index 0 to len(list)-2.

    • This loop represents the current position where we want to place the minimum element.

  2. Set min_index:

    • Initially, we assume the first unsorted element is the minimum.

  3. Inner loop (j): Scans the rest of the list to find the true minimum.

    • If a smaller value is found, min_index is updated.

  4. Swap if necessary:

    • Only swap if the minimum index found is different from i.

    • This avoids unnecessary swaps when the current element is already the minimum.

  5. Return sorted list.


Step 3: Run the Function

my_list = [2, 6, 5, 1, 3, 4]
sorted_list = selection_sort(my_list)
print(sorted_list)

Output:

[1, 2, 3, 4, 5, 6]

Step 4: Notes & Observations

  • After the first pass, the smallest element is in its correct position.

  • After the second pass, the second smallest element is in its correct position.

  • This continues until the entire list is sorted.

  • Time Complexity: O(n²) in all cases.

  • Space Complexity: O(1) (in-place sorting).

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top