Selection Sort

Selection Sort

Example with Explanation:

Let’s take the array: [64, 25, 12, 22, 11]

Step-by-Step Execution:

  1. First pass (i=0):

    • Initial array: [64, 25, 12, 22, 11]

    • Find the smallest element from the entire array (from index 1 to 4).

    • The smallest element is 11 at index 4.

    • Swap 64 and 11.

    • Array after swap: [11, 25, 12, 22, 64]

  2. Second pass (i=1):

    • Find the smallest element from [25, 12, 22, 64].

    • The smallest element is 12 at index 2.

    • Swap 25 and 12.

    • Array after swap: [11, 12, 25, 22, 64]

  3. Third pass (i=2):

    • Find the smallest element from [25, 22, 64].

    • The smallest element is 22 at index 3.

    • Swap 25 and 22.

    • Array after swap: [11, 12, 22, 25, 64]

  4. Fourth pass (i=3):

    • Find the smallest element from [25, 64].

    • The smallest element is 25 (no swap needed).

    • Array remains: [11, 12, 22, 25, 64]

  5. End of sorting:

    • The array is now sorted: [11, 12, 22, 25, 64]

1. Pseudocode for Selection Sort:

SelectionSort(arr, n):
    For i from 0 to n-1:
        minIndex = i
        For j from i+1 to n:
            If arr[j] < arr[minIndex]:
                minIndex = j
        If minIndex != i:
            Swap arr[i] and arr[minIndex]

2. Algorithm for Selection Sort:

  1. Input: An array arr[] of size n.

  2. Process:

    • Loop through each element in the array.

    • In each iteration, find the smallest element from the unsorted portion of the array.

    • Swap the smallest element found with the first element of the unsorted portion.

    • Repeat this process for all elements until the array is sorted.

  3. Output: The sorted array.


3. C Code for Selection Sort:

Function to Perform Selection Sort:

#include <stdio.h>
// Function to perform Selection Sort
void selectionSort(int arr[], int n) {
    int i, j, minIndex, temp;

    // Traverse through all array elements
    for (i = 0; i < n - 1; i++) {
        minIndex = i;

        // Find the minimum element in the unsorted portion of the array
        for (j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }

        // Swap the found minimum element with the first element
        if (minIndex != i) {
            temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
        }
    }
}

4. Explanation of the Code:

  • selectionSort function:

    • It loops through each element in the array (i from 0 to n-1).

    • For each iteration, it finds the smallest element in the unsorted portion (arr[j] from i+1 to n).

    • If a smaller element is found, minIndex is updated.

    • After the inner loop, the smallest element (arr[minIndex]) is swapped with the element at the current position i.

5. Complexity Analysis ( Source : ChatGpt - well explained )