Program to sort an array using Selection Sort in c

Program to sort array using Selection Sort

Program to sort an array using Selection Sort in c

Sorting is an essential operation in computer programming that arranges data in a specific order. Selection Sort is one of the simplest sorting algorithms that sort an array by repeatedly finding the minimum element from the unsorted part of the array and putting it at the beginning of the array. In this article, we will discuss the implementation of Selection Sort in C language and its optimization techniques for better performance.

Selection Sort Algorithm

The Selection Sort algorithm works by selecting the minimum element from the unsorted part of the array and swapping it with the first element of the unsorted part. The algorithm then proceeds to select the minimum element from the remaining unsorted part of the array and swap it with the second element of the unsorted part. This process continues until the entire array is sorted.

#include<stdio.h>
#include<conio.h>

void main()
{
    int array[20], n, i, j, pos, temp;
    clrscr();

    printf("Enter total number of elements :");
    scanf("%d", &n);

    for (i = 0; i < n; i++)
    {
        printf("\nEnter element number %d : ", i+1);
        scanf("%d", &array[i]);
    }

    for (i = 0; i < (n - 1); i++)
    {
        pos = i;
        for (j = i + 1; j < n; j++)
        {
            if (array[pos] > array[j])
                pos = j;
        }
        if (pos != i)
        {
            temp = array[i];
            array[i] = array[pos];
            array[pos] = temp;
        }
    }

    printf("\nSorted elements :");

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

    getch();
}

Output:-

Enter total number of elements :11

Enter element number 1 : 54

Enter element number 2 : 189

Enter element number 3 : 445

Enter element number 4 : 178

Enter element number 5 : 456

Enter element number 6 : 258

Enter element number 7 : 02

Enter element number 8 : 80

Enter element number 9 : 885

Enter element number 10 : 1100

Enter element number 11 : 786

Sorted elements :2
54
80
178
189
258
445
456
786
885
1100
That's all in this post, we will talk on the next topic in the next post, to read the full chapter of c language, click on the link and start reading.
c language Tutorial
Previous articleFirewall Rules pdf | rules of firewall – sirfpadhai
Next articleC++ tutorial for beginners

LEAVE A REPLY

Please enter your comment!
Please enter your name here