BlogsDope image BlogsDope

Sorting an array using selection sort in C

May 27, 2017 C ARRAY SORT ALGORITHM LOOP 16811

Selection sort is one of the simplest sorting algorithms. It is similar to the hand picking where we take the smallest element and put it in the first position and the second smallest at the second position and so on. It is also similar. We first check for smallest element in the array and swap it with the first element of the array. Again, we check for the smallest number in a subarray excluding the first element of the array as it is where it should be (at the first position) and put it in the second position of the array. We continue repeating this process until the array gets sorted.

The time complexity of selection sort is (O(n2)).

We follow the following steps to perform selection sort:

  1. Start from the first element in the array and search for the smallest element in the array.
  2. Swap the first element with the smallest element of the array.
  3. Take a subarray (excluding the first element of the array as it is at its place) and search for the smallest number in the subarray (second smallest number of the entire array) and swap it with the first element of the array (second element of the entire array).
  4. Repeat the steps 2 and 3 with new subarrays until the array gets sorted.

Working of selection sort:


Initial array

16 19 11 15 10 12 14

 First iteration

16 19 11 15 10 12 14
10 19 11 15 16 12 14

Second iteration

10 19 11 15 16 12 14
10 11 19 15 16 12 14

Third iteration

10 11 19 15 16 12 14
10 11 12 15 16 19 14

Fourth iteration

10 11 12 15 16 19 14
10 11 12 14 16 19 15

Fifth iteration

10 11 12 14 16 19 15
10 11 12 14 15 19 16

Sixth iteration

10 11 12 14 15 19 16
10 11 12 14 15 16 19

Final array

10 11 12 14 15 16 19

Let’s code this in C

#include <stdio.h>
#include <math.h>

int main()
{
    int a[] = {16, 19, 11, 15, 10, 12, 14};
    int i,j;

    i = 0;
    while (i<7)
    {

        //finding the smallest number in the subarray
        int index_of_smallest = i;
        for(j=i; j<7; j++)
        {
            if (a[j]<a[index_of_smallest])
                index_of_smallest = j;
        }

        //swapping
        int temp = a[i];
        a[i] = a[index_of_smallest];
        a[index_of_smallest] = temp;

        i++;
    }

    for(i=0;i<7;i++)
        printf("%d\n",a[i]);

    return 0;
}

The code is just an implementation of the above explanation. We are finding the smallest number in the subarray after ‘i’ by using the ‘for’ loop and then swapping it with the first element of the subarray.


Liked the post?
Developer and founder of CodesDope.
Editor's Picks
0 COMMENT

Please login to view or add comment(s).