C Program to Sort an Array Using Selection Sort


Sorting is a procedure in which the given elements are arranged in ascending or descending order. For example if the elements of an array are –

5, 11, 15, 8, 7, 54, 63, 44

After sorting these elements in ascending order, the elements would be –

5, 7, 8, 11, 15, 44, 54, 63

What is Selection Sort is :

Suppose that you are given some numbers and asked to arrange them is ascending order. The most intuitive way to do this would be to find the smallest number and put it in the first place and then find the second smallest number and put it in the second place and so on. This is the simple technique on which selection sort is based. It is named so because in each pass it selects the smallest element and keeps it in its exact place. Let’s now see the c program to sort an array using selection sort.

C Program ►►

#include<stdio.h>
#include<conio.h>

void main()
{
   int size,arr[100],i,j,min,temp;

   printf("Enter the Number of Elements : ");
   scanf("%d",&size);

   printf("\nEnter the elements of the Array : ");
   
   for(int i=0;i<size;i++) {
   printf("\nArray[%d] = ",i+1);
   scanf("%d",&arr[i]);
   }

   /* Selection Sort */
   for(i=0;i<size-1;i++)
   {

       /*Find the index of smallest element*/

       min=i;
       for(j=i+1;j<size;j++)
       {
       
             if(arr[min]>arr[j])
             min=j;
       }

             if(min!=i)
             {
                    temp=arr[i];
                    arr[i]=arr[min];
                    arr[min]=temp;
             }
            
   } // end of outside for

   printf("\nSorted List is : \n");
   
   for(i=0;i<size;i++)
   printf("%d\t",arr[i]);
   getch();
   
}

Explanation ►► 

Each iteration of outer for loop corresponds to a single pass. In each iteration of outer for loop we have to exchange arr[i] with the smallest element among arr[i+1], arr[i+2],…..arr[n-1]. The inner loop is used to find the index of smallest element and it is stored in min variable. Initially variable min is initialized with i. After this, arr[min] is compared with each of the elements arr[i+1], arr[i+2]…..arr[n-1] and whenever we get a smaller element, its index is assigned to min.

After finding the smallest element, it is exchanged with arr[i]. We have preceded this swap operation with a condition to avoid swapping of an element with itself. This situation arises when an element is already in its proper place.

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