SELECTION SORT :
There are several methods for sorting an array, selection sort is one of them.
Let us take an unsorted list of elements and sort them by applying this algorithm.
Elements of the array -
9 3 6 7 1 5
Pass 1:
9 3 6 7 1 5 arr[0] > arr[1], Exchange
3 9 6 7 1 5 arr[0] < arr[2]
3 9 6 7 1 5 arr[0] < arr[3]
3 9 6 7 1 5 arr[0] > arr[4], Exchange
1 9 6 7 3 5 arr[0] < arr[5]
1 9 6 7 3 5
Pass 2:
1 9 6 7 3 5 arr[1] > arr[2], Exchange
1 6 9 7 3 5 arr[1] < arr[3]
1 6 9 7 3 5 arr[1] > arr[4], Exchange
1 3 9 7 6 5 arr[1] < arr[5]
1 3 9 7 6 5
Pass 3:
1 3 9 7 6 5 arr[2] > arr[3], Exchange
1 3 7 9 6 5 arr[2] > arr[4], Exchange
1 3 6 9 7 5 arr[2] > arr[5], exchange
1 3 5 9 7 6
Pass 4:
1 3 5 9 7 6 arr[3] > arr[4], Exchange
1 3 5 7 9 6 arr[3] > arr[5], Exchange
1 3 5 6 9 7
Pass 5:
1 3 5 6 9 7 arr[4] > arr[5], Exchange
1 3 5 6 7 9
Sorted array is :
1 3 5 6 7 9
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[50],i,j,n,temp;
clrscr();
printf("Enter how many number you want to display: ");
scanf("%d",&n); printf("Enter %d elements\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("\nElements before sorted are: \n");
for(i=0;i<n;i++)
{
printf("%d\t",arr[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
printf("\nElements after sorted are: \n");
for(i=0;i<n;i++)
{
printf("%d\t",arr[i]);
}
getch();
}
#include<conio.h>
void main()
{
int arr[50],i,j,n,temp;
clrscr();
printf("Enter how many number you want to display: ");
scanf("%d",&n); printf("Enter %d elements\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("\nElements before sorted are: \n");
for(i=0;i<n;i++)
{
printf("%d\t",arr[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
printf("\nElements after sorted are: \n");
for(i=0;i<n;i++)
{
printf("%d\t",arr[i]);
}
getch();
}
Comments
Post a Comment