Selection Sort

Selection Sort

Selection Sort works by repeatedly finding the minimum element from the unsorted part of the array and placing it at the beginning. The algorithm divides the array into two parts: the sorted part and the unsorted part. In each iteration, it selects the smallest element from the unsorted part and swaps it with the first element of the unsorted part.

Here's a step-by-step explanation of the Selection Sort algorithm:

Start with an unsorted array of elements.

Selection Sort has a time complexity of O(n^2), where n is the number of elements in the array. It is not the most efficient sorting algorithm for large datasets but can be suitable for small arrays or partially sorted arrays.

Selection Sort Code in Python

def selection_sort(arr):

    n = len(arr)

    # Traverse through all array elements

    for i in range(n-1):

        # Find the minimum element in the unsorted part

        min_index = i

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

            if arr[j] < arr[min_index]:

                min_index = j

        # Swap the minimum element with the first element of the unsorted part

        arr[i], arr[min_index] = arr[min_index], arr[i]

# Example usage:

array = [5, 2, 8, 1, 9, 3]


print("Sorted array:", array)