A blog for technology, SEO tips, website development and open source programming.

Data Structure – Selection sort algorithm

0 801

The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right. (The example code is written in C programming language)

Example: C Program to to arrange number in ascending order using Selection sort technique.

#include
void selection_sort(int a[],int n);
{
int i,j,pos,small,temp;
for(i=0;i<n-1;i++)
{
small=a[i]; /* Initial small number in ith pass */
pos=i; /* Position of smaller number */
/* Find the minimum of remaining elements along with the position */
for(j=i+1;j<n;j++)
{
if(a[i]<small)
{
small=a[j];
pos=j;
}
}
/* Exchange ith item with least item */
temp=a[pos];
a[pos] = a[i];
a[i]=temp;
}
}
void main()
{
int i,n,a[20];
printf("Enter the number of elements to sort");
scanf("%d",&n);
printf("Enter %d elements to sort ",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
selection_sort(a,n)
printf("The sort elements are");
for(i=0;i<n;i++)
printf("%d",&a[i]);
}

Leave a Reply

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More