Add

Selection Sort Data Structure in C Program

 


Selection Sort is the most simplest Sorting Technique, in this sorting technique first finds the smallest or largest element (depending on the order that you want to do) and swaps the smallest or largest elements with the corresponding element.

Data Structure - Selection Sort Example using C program

/*Selection Sort - C program to sort an Array

in Ascending and Descending Order.*/


#include <stdio.h>

#define MAX 100

int main()

{

    int arr[MAX],limit;

    int i,j,temp,position;    

    printf("Enter total number of elements: ");

    scanf("%d",&limit);    

    /*Read array*/

    printf("Enter array elements: \n");

    for(i=0; i<limit; i++)

    {

        printf("Enter element %3d: ",i+1);

        scanf("%d",&arr[i]);

    }    

    /*sort elements in Ascending Order*/

    for(i=0; i<(limit); i++)

    {

        position=i;

        for(j=i+1; j<limit; j++)

        {

            if(arr[position]>arr[j])

            {

                position=j;

            }

            if(position!=i)

            {

                temp=arr[i];

                arr[i]=arr[position];

                arr[position]=temp;               

            }

        }

    }

    printf("Array elements in Ascending Order:\n");

    for(i=0; i<limit; i++)

        printf("%d ",arr[i]);    

    printf("\n");        

    /*sort elements in Descending Order*/

    for(i=0; i<(limit); i++)

    {

        position=i;

        for(j=i+1; j<limit; j++)

        {

            if(arr[position]<arr[j])

            {

                position=j;

            }

            if(position!=i)

            {

                temp=arr[i];

                arr[i]=arr[position];

                arr[position]=temp;               

            }

        }

    }

    printf("Array elements in Descending Order:\n");

    for(i=0; i<limit; i++)

        printf("%d ",arr[i]);

    printf("\n");    

    return 0;

}

Output

    Enter total number of elements: 5

    Enter array elements:

    Enter element 1: 11

    Enter element 2: 2

    Enter element 3: 1

    Enter element 4: 223

    Enter element 5: 4

    Array elements in Ascending Order:

    1 2 4 11 223

    Array elements in Descending Order:

    223 11 4 2 1

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.