Selection Sorting using C

 


      
Selection sort is a simple, in-place, comparison-based sorting algorithm. It works by repeatedly finding the minimum for ascending order (or maximum for descending order) element from the unsorted portion of the list and placing it at the beginning of the sorted portion.


0 1 2 3 4 -> Indices

--------------------------

9 7 5 2 8 -> Elements of array

min=a[0];

a[1]<min

7<9

min=7

pos=1

a[2]<min

5<7

min=5

pos=2

a[3]<min

2<5T

min=2

pos-3

a[4]<min

8<2F

2 7 5 9 8

min=7

pos=1


a[2]<min

5<7T

min=5

pos=2

a[3]<min

9<5F

a[4]<min

8<5F


2 5 7 9 8

min=7

pos=2

a[3]<min

9<7F

a[4]<min

8<7F


min=9

pos=3

a[4]<min

8<9T

min=8

pos=4


2 5 7 8 9

/*Program to sort elements of array using selection sort technique*/


#include<stdio.h>

main()

{

int a[ 50 ],n,i,min,pos,temp,j;

printf("\nEnter the value for n ");

scanf("%d",&n);

printf("\nEnter the elements of array ");

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

{

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

}

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

{

  min=a[ i ];

  pos=i;

 for(j=pos+1;j<n;j++)

   {

if(a[ j ]<min)

{

  min=a[ j ];

  pos=j;

}

   }

 temp=a[ i ];

  a[ i ]=min;

  a[ pos ]=temp;

}

printf("\nElements of array after selection sorting \n");

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

{

  printf("%3d",a[ i ]);

}

}


OR


#include <stdio.h>

int main()

{

int a[ 50 ],n,i,pos,temp,j;

printf("\nEnter the value for n ");

scanf("%d",&n);

printf("\nEnter the elements of array ");

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

{

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

}

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

{

  pos=i;

 for(j=pos+1;j<n;j++)

   {

if(a[ j ]<a[ pos ])

{

  pos=j;

}

   }

if(pos!=i)

 {

  temp=a[ i ];

  a[ i ]=a[ pos ];

  a[ pos ]=temp;

 }

}

printf("\nElements of array after selection sorting \n");

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

{

  printf("%3d",a[ i ]);

}

    return 0;

}

CLICK ON THE BELOW IMAGE TO SEE THE VIDEO DEMONSTRATION OF PROGRAM




Comments