C Program for Selection Sort

C Program for Selection Sort

Program for selection sort in c; Through this tutorial, we will learn how to implement a program for selection sort in c using 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.

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 output 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 output 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 	

Recommended C Programs

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

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