Tuesday, 15 October 2024

Selection sort

 Sort the following data by using selection sort 12, 11, 13, 5, 6

Steps for Selection sort:

  1. Find the minimum element in the array and swap it with the first element.

  2. Repeat the process for the remaining unsorted part of the array.

Sorting Process:

Initial array: 12, 11, 13, 5, 6

  1. Step 1 (Find min in 12, 11, 13, 5, 6):

    • Min = 5

    • Swap 5 with the first element (12).

    • Array: 5, 11, 13, 12, 6

  2. Step 2 (Find min in 11, 13, 12, 6):

    • Min = 6

    • Swap 6 with the second element (11).

    • Array: 5, 6, 13, 12, 11

  3. Step 3 (Find min in 13, 12, 11):

    • Min = 11

    • Swap 11 with the third element (13).

    • Array: 5, 6, 11, 12, 13

  4. Step 4 (Find min in 12, 13):

    • Min = 12

    • No need to swap as 12 is already in place.

    • Array: 5, 6, 11, 12, 13

Now the array is sorted: 5, 6, 11, 12, 13



#include <stdio.h>


int main() {

    int A[5] = {12, 11, 13, 5, 6}; // Initialize the array

    int i, j, x;


    // Sorting the array using Selection Logic

    for (i = 0; i < 5; i++) // outer loop i = 0 to i < 5 (i.e., 0 to 4).

      {

        for (j = i + 1; j < 5; j++)//inner loop for comparison 

       {

            if (A[i] > A[j]) {

                // Swap elements A[i] and A[j]

                x = A[i];

                A[i] = A[j];

                A[j] = x;

            }

        }

    }


    // Display the sorted array

    printf("After Sorting: ");

    for (i = 0; i < 5; i++) {

        printf("%d ", A[i]);

    }

    printf("\n");


    return 0;

}




Explanation 

  1. Step 1 (Find minimum in 12, 11, 13, 5, 6):

    • Outer loop (i = 0): The first element is 12.

    • Inner loop compares it with the rest:

      • Compare 12 with 11 → 12 > 11, so no swap yet.

      • Compare 12 with 13 → No change.

      • Compare 12 with 5 → 12 > 5, swap 12 with 5.

      • Array becomes: {5, 11, 13, 12, 6}


  1. Step 2 (Find minimum in 11, 13, 12, 6):

    • Outer loop (i = 1): The current element is 11.

    • Inner loop compares it with the rest:

      • Compare 11 with 13 → No change.

      • Compare 11 with 12 → No change.

      • Compare 11 with 6 → 11 > 6, swap 11 with 6.

      • Array becomes: {5, 6, 13, 12, 11}


  1. Step 3 (Find minimum in 13, 12, 11):

    • Outer loop (i = 2): The current element is 13.

    • Inner loop compares it with the rest:

      • Compare 13 with 12 → 13 > 12, swap 13 with 12.

      • Array becomes: {5, 6, 12, 13, 11}

      • Compare 12 with 11 → 12 > 11, swap 12 with 11.

      • Array becomes: {5, 6, 11, 13, 12}

  1. Step 4 (Find minimum in 13, 12):

    • Outer loop (i = 3): The current element is 13.

    • Inner loop compares it with 12:

      • 13 > 12, so swap 13 with 12.

      • Array becomes: {5, 6, 11, 12, 13}


  1. Step 5 (Only one element left):

    • Outer loop (i = 4): No comparison needed, as only one element remains.