Selection Sort in C Programming Langauge

In this Searching and Sorting in C Programs, we will have a look at how to write a Program of Selection Sort C Programming Language.

Sorting algorithm supports two parts.

  1. The first part is already sorted
  2. The second part, which still needs to be sorted.

The algorithm works by relying on the finding of a minimal element (taking into account the order of growth) from the unsorted part and placing it at the end of the sorted part.

arr [] = 64 25 12 22 11

// Find the minimal element in arr [0 … 4]
// and place it in the beginning
11 25 12 22 64

// Find the minimal element in arr [1 … 4]
// and place it in the beginning arr [1 … 4]
11 12 25 22 64

// Find the minimal element in arr [2 … 4]
// and place it in the beginning arr [2 … 4]
11 12 22 25 64

// Find the minimal element in arr [3 … 4]
// and place it in the beginning arr [3 … 4]
11 12 22 25 64

C Program of Selection Sort

#include <stdio.h>

int main()

{

  int array[100], n, c, d, position, swap;

  printf("Enter number of elements\n");

  scanf("%d", &n);

  printf("Enter %d integers\n", n);

  for (c = 0; c < n; c++)

    scanf("%d", &array[c]);

  for (c = 0; c < (n - 1); c++)

  {

    position = c;

    for (d = c + 1; d < n; d++)

    {

      if (array[position] > array[d])

        position = d;

    }

    if (position != c)

    {

      swap = array[c];

      array[c] = array[position];

      array[position] = swap;

    }

  }

  printf("Sorted list in ascending order:\n");

  for (c = 0; c < n; c++)

    printf("%d\n", array[c]);

  return 0;

}

Output:

Enter number of elements

5

Enter 5 integers

3

1

2

4

5

Sorted list in ascending order

1

2

3

4

5

Leave a Reply

Your email address will not be published. Required fields are marked *

Shopping cart