Selection Sort Using C

                   Hello guys, selection sort is one of the basic algorithm and programming concept which we need from the very beginning to lifetime of programming. In most of the cases in programming, we need sorted input for the execution of the code in proper manner. But its not a logical habit to ask the use to enter in the sorted manner. So this is one of the basic sorting concept one should know.

Description:
                     Well, in this concept, the sorting technique lies on a concept of comparing again and again the elements of array which is taken. This simply shows that we have to use looping concept. Here easiest way is to use for loop. We have to take two for loops, one for selection of one element from array and another one for the rest of the elements which are to be compared. The format of the for loop will be like this,

for( i=0; i<n-1; i++)                       // where n is the number of elements
{
      for( j=i+1; j<n; j++)
      {
          //code
      }
}

The outer loop starts from the zeroth index and ends before last element occurs. The inner loop starts from right next index of the element selected. The outer loop element selects one element and inner loop compares it with the other elements. When i reaches up to (n-1)th element, then there is no need to compare anymore, because the array is already sorted. The sorting logic is also simple. This is the pattern we sort.

if( a[i]> a[j] )
{
     temp=a[i];
     a[i]=a[j];
     a[j]=a[i];
}
Here temp is a variable which stores data temporarily. Check out a sample output.

Sample output:

Program Code:
#include<stdio.h>
int main()
{
    int a[100],n,i,j,temp;
    printf("Enter the number of elements:");
    scanf("%d",&n);
    printf("\nEnter the numbers you want to sort:");
    for(i=0;i<n;i++)
    {
  scanf("%d",&a[i]);
    }
    for(i=0;i<n-1;i++)
    {
  for(j=i+1;j<n;j++)
  {
   if(a[i]>a[j]) //for decreasing order use "<"
            {
                 temp=a[i];
                 a[i]=a[j];
                 a[j]=temp;
             }
         }                
    }
    printf("\nThe sorted form of the input:");
    for(i=0;i<n;i++)
    {
         printf("%d  ",a[i]);
    }
    getch();
    return 0;
}

Well that's it guys. Any suggestions or queries??  Write them below.;)

Comments

Popular posts from this blog

Non Restoring Division Algorithm Implementation in C

Bit Stuffing Code Implementation in Java

Hackerrank Modified Kaprekar Numbers Solution