Selection Sort in Python

Selection Sort in Python

 Selection sort is an algorithm for sorting an array by repeatedly selecting the minimum element (or maximum element) from the unsorted portion of the array and placing it at the beginning (or end). It works by iterating through the array and selecting the minimum element, and then swapping it with the first element of the unsorted portion of the array. This process is repeated until the array is sorted.


Here is an example of how you might implement selection sort in Python:

def selection_sort(array):

    n = len(array)

    for i in range(n - 1):

        min_index = i

        for j in range(i + 1, n):

            if array[j] < array[min_index]:

                min_index = j

        array[i], array[min_index] = array[min_index], array[i]

    return array


array = [4, 3, 2, 1]

sorted_array = selection_sort(array)

print(sorted_array) # Outputs [1, 2, 3, 4]

In this example, the selection_sort function takes an array as input and returns the sorted array. It uses two nested for loops to iterate through the array and find the minimum element. The inner loop iterates through the unsorted portion of the array and keeps track of the minimum element, and the outer loop iterates through the array from the beginning to the end, swapping the minimum element with the first element of the unsorted portion of the array each time.

Post a Comment

0 Comments