Write a C Program to sort a set of number using Selection Sort
Algorithm:
ssort(array[],n)
{
for ( i = 0 to n-1 )
{
position <- i;
for ( j = i + 1 to n )
{
if ( array[position] > array[j] )
position <- j;
}
if ( position != i )
{
temp <- array[i];
array[i] <- array[position];
array[position] <- temp;
}
}
}
Program:
/* Using User Defined Method */
#include <stdio.h>
void printar(int array[], int n)
{
int i;
for ( i = 0 ; i < n ; i++ )
printf("%d ", array[i]);
printf("\n\n");
}
void ssort(int array[], int n)
{
int i,j,position,temp;
for ( i = 0 ; i < ( n - 1 ) ; i++ )
{
position = i;
for ( j = i + 1 ; j < n ; j++ )
{
if ( array[position] > array[j] )
position = j;
}
if ( position != i )
{
temp = array[i];
array[i] = array[position];
array[position] = temp;
printar(array,n);
}
}
}
void main()
{
int array[100], i,n;
printf("\nEnter number of elements: ");
scanf("%d", &n);
printf("\nEnter %d integers: ", n);
for ( i = 0 ; i < n ; i++ )
scanf("%d", &array[i]);
printf("\nProcessing... \n\n");
ssort(array,n);
printf("\n\nSorted list in ascending order: ");
printar(array,n);
}
/* Without Using User Defined Method */
#include<stdio.h>
void main()
{
int a[10],i,j,k,t;
printf("Enter 10 values:\n");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
for(i=0;i<10;i++)
{
k=i;
for(j=i;j<10;j++)
{
if(a[k]>a[j])
k=j;
}
if(k!=i)
{
t=a[k];
a[k]=a[i];
a[i]=t;
}
}
printf("Sorted Array is:\n");
for(i=0;i<10;i++)
printf("%d\n",a[i]);
}
Output:
Conclusion:
The given elements are sorted. The smallest element gets its position at the beginning of given array and the sorting process is continued recursively from the next location as the starting of the array. The program has run correctly.
Comments
Post a Comment