C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Arrays in C

Selection Sort Program

C Program: Selection Sort Program

C

#include <stdio.h>

 

int main() {

    int arr[100], n, i, j, minIndex, temp;

 

    // Input number of elements

    printf("Enter number of elements: ");

    scanf("%d", &n);

 

    // Input array elements

    printf("Enter %d elements:\n", n);

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

        scanf("%d", &arr[i]);

    }

 

    // Selection Sort algorithm

    for(i = 0; i < n - 1; i++) {

        minIndex = i; // Assume current as minimum

        for(j = i + 1; j < n; j++) {

            if(arr[j] < arr[minIndex])

                minIndex = j; // Update index of smaller element

        }

 

        // Swap if a smaller element is found

        if(minIndex != i) {

            temp = arr[i];

            arr[i] = arr[minIndex];

            arr[minIndex] = temp;

        }

    }

 

    // Display sorted array

    printf("\nSorted array in ascending order:\n");

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

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

    }

 

    printf("\n");

    return 0;

}

Output

 
INPUT :
Enter number of elements: 5
Enter 5 elements:
64 25 12 22 11

OUTPUT :
Sorted array in ascending order:
11 12 22 25 64

Explanation

  1. Selection Sort finds the smallest element in the unsorted part of the array and swaps it with the first unsorted element.
  2. The process repeats until all elements are sorted.
  3. Unlike Bubble Sort, Selection Sort makes fewer swaps, making it more efficient in terms of data movement.

 

Algorithm Steps

  1. Start from the first element (i = 0).
  2. Find the smallest element among arr[i] to arr[n-1].
  3. Swap it with arr[i].
  4. Move to the next element and repeat the process until the array is sorted.