India's Largest Free Online Education Platform

C program for selection Sort

C program for selection Sort

#include <stdio.h>
#include <stdlib.h>
int selection_sort(int,int[]);
int main()
{
  int n;
  int arr[100];
  printf("\n This is a simple program for selection sort\n");
  printf("\n Enter the size of array you want\n");
  scanf("%d",&n);   // taking input 
 
  printf("\n Now Enter the elements of array\n");
  for(int i=0;i<n;i++)
  scanf("%d",&arr[i]);  // taking input of array elements

  printf("Array elements entered by you is:\n ");
  for(int i=0;i<n;i++)
  printf("%d\t",arr[i]);   // printing entered array elements
  
  printf("\n\n Array elements after sorting :\n");
  selectioin_sort(n,arr);   // function call
  printf("\n Sorted array elements after selection sort");
  return 0;
}

int selectioin_sort(int n,int arr[])     // function definition
{
  int smallest;
  for (int j=0;j<n-1;j++)
    { 
        smallest=arr[j];
        for (int i=1+j;i<n;i++)
          {
              if(smallest>arr[i])
                 {
                    smallest=arr[i];
                    arr[i]=arr[j];
                    arr[j]=smallest;
                 }
          }
   }
for ( int k=0;k<n;k++)    // displaying final array
printf("%d \t",arr[k]);
return 0;
}

Output:

C program for selection sort
Output:1
C program for selection sort
Output:2

The above code can’t be directly copy-pasted. You must have to type with your own hand. This is made for your better future. 

Are you made for copy paste?

Absolutely “NO“. 

Then, try hard to understand this code and type with your own.

Leave a Reply

Your email address will not be published. Required fields are marked *

error: Content is protected !!