Selection Sort algorithm

Selection sorting is conceptually the most simplest sorting algorithm. This algorithm first finds the smallest element in the array and exchanges it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and continues in this way until the entire array is sorted.

Sorting using Selection Sort Algorithm

void selectionSort(int a[], int size)
{
  int i, j, min, temp;
  for(i=0; i < size-1; i++ )
  {
    min = i;   //setting min as i
    for(j=i+1; j < size; j++)
    {
      if(a[j] < a[min])   //if element at j is less than element at min position
      {
       min = j;    //then set min as j
      }
    }
   temp = a[i];
   a[i] = a[min];
   a[min] = temp;
  }
}

Selection Sorting in Data Structures

Example: C program, Function to arrange number in ascending order using Selection sort technique.

#include<stdio.h>
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]);
}
 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

WordPress.com.

Up ↑

%d bloggers like this: