Techie Programmer

Selection Sort Algorithm in C

Selection Sort is a simple comparison-based sorting algorithm. It works by repeatedly selecting the smallest (or largest, depending on the order) element from the unsorted part of the array and swapping it with the first unsorted element. This process continues until the entire array is sorted.

You can get the complete code from Github

Steps of Selection Sort:
1. Start from the first element: Consider the first element of the array as the minimum.

2. Find the minimum element: Traverse the remaining unsorted part of the array to find the smallest (or largest) element.

3. Swap the elements: Swap the found minimum element with the first unsorted element.

4. Move the boundary: The boundary of sorted and unsorted sections moves one element to the right.

5. Repeat the process until all elements are sorted.

selectionsort.c
1 #include<stdio.h>
2 int main() {
3     int Arr[] = {43,45,98,23,21,5,1,8,2,6,77,18,4};
4     int n = sizeof(Arr)/sizeof(Arr[0]);
5     int i,j,s;
6 
7     printf("Before Sort:\n");
8     for(i = 0;i < n;i++) {
9         printf("%d ",Arr[i]);
10     }
11     printf("\n");
12 
13     for(i = 0;i < n;i++) {
14         s = i;
15         for(j = i+1;j < n;j++) {
16             if(Arr[s] > Arr[j]) {
17                 s = j;
18             }
19         }
20         if(i != s) {
21             j = Arr[i];
22             Arr[i] = Arr[s];
23             Arr[s] = j;
24         }
25     }
26 
27     printf("After Sort:\n");
28     for(i = 0;i < n;i++) {
29         printf("%d ",Arr[i]);
30     }
31     printf("\n");
32 
33     return 0;
34 }