Selection sort is based on the follwing idea:
Selecting the largest array element and swapping it with the last array element leaves an unsorted list whose size is 1 less than the size of the original list. If we repeat this step again on the usorted list we will have an ordered list of size 2 and an unsorted list size n-2. When we repeat thist until the size of the unsorted list becomes one, the result will be a sorted list.
Write a program to implement this algorithm.
#include <stdio.h>
void main()
{
int i,j,min,pos,arr[200],size;
clrscr();
printf("Enter the number of elements of array:");
scanf("%d",&size);
printf("Enter the elements fo array\n");
for(i=1;i<=size;i++)
scanf("%d",&arr[i]);
for(i=1;iA<size-1;i++)
{
min=arr[i];
pos=i;
for(j=i+1;j<size;j++)
{
if(arr[j]<min)
{
min=arr[j];
pos=j;
}
}
arr[pos]=arr[i];
arr[i]=min;
}
for(i=1;i<=size;i++)
printf("%d ",arr[i]);
getch();
}
Selecting the largest array element and swapping it with the last array element leaves an unsorted list whose size is 1 less than the size of the original list. If we repeat this step again on the usorted list we will have an ordered list of size 2 and an unsorted list size n-2. When we repeat thist until the size of the unsorted list becomes one, the result will be a sorted list.
Write a program to implement this algorithm.
#include <stdio.h>
void main()
{
int i,j,min,pos,arr[200],size;
clrscr();
printf("Enter the number of elements of array:");
scanf("%d",&size);
printf("Enter the elements fo array\n");
for(i=1;i<=size;i++)
scanf("%d",&arr[i]);
for(i=1;iA<size-1;i++)
{
min=arr[i];
pos=i;
for(j=i+1;j<size;j++)
{
if(arr[j]<min)
{
min=arr[j];
pos=j;
}
}
arr[pos]=arr[i];
arr[i]=min;
}
for(i=1;i<=size;i++)
printf("%d ",arr[i]);
getch();
}
No comments:
Post a Comment