C Program for Selection Sort

In this tutorial, i am going to show you how to implement a program for selection sort in c with the help of for loop and while loop.

Selection sort works by taking the smallest element in an unsorted array and bringing it to the front. You’ll go through each item (from left to right) until you find the smallest one. The first item in the array is now sorted, while the rest of the array is unsorted.

All C Program for Selection Sort

  • C Program for Selection Sort using For Loop
  • C Program for Selection Sort using While Loop

C Program for Selection Sort using For Loop

#include <stdio.h>
int main()
{
    int a[100], number, i, j, temp;
    printf("\n Please Enter the total Number of Elements  :  ");
    scanf("%d", &number);
    printf("\n Please Enter the Array Elements  :  ");
    for(i = 0; i < number; i++)
        scanf("%d", &a[i]);
    for(i = 0; i < number; i++) {
        for(j = i + 1; j < number; j++) {
            if(a[i] > a[j]) {
                temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
    }
    printf("\n Selection Sort Result : ");
    for(i = 0; i < number; i++)  {
        printf(" %d \t", a[i]);
    }
    printf("\n");
    return 0;
}

The result of the above c program; is as follows:

Please Enter the total Number of Elements  :  5
Please Enter the Array Elements  :  1 5 7 6 2
Selection Sort Result :  1 	 2 	 5 	 6 	 7 	

C Program for Selection Sort using While Loop

#include <stdio.h>
int main()
{
    int a[100], val, i, j, temp;
    printf("\n Please Enter the total No. of Elements  :  ");
    scanf("%d", &val);
    printf("\n Please Enter the Array Elements  :  ");
    for(i = 0; i < val; i++)
        scanf("%d", &a[i]);
    
    i = 0;
    while( i < val) {
        j = i + 1;
        while( j < val) {
            if(a[i] > a[j]) {
                temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
            j++;
        }
        i++;
    }
    printf("\n Result : ");
    for(i = 0; i < val; i++)  {
        printf(" %d \t", a[i]);
    }
    printf("\n");
    return 0;
}

The result of the above c program; is as follows:

Please Enter the total No. of Elements  :  5
Please Enter the Array Elements  :  5 4 2 6 9
Result :  2 	 4 	 5 	 6 	 9 	

More C Programming Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.