Selection sort

 In selection sort, there is an unsorted array of size n, and we'll consider a sorted array of size zero in it.

Initially, we will pick the first element of array and swap it with the smallest element of remaining array. And now the size of our sorted array becomes 1 and size of unsorted array decreases by 1. But still the size of array remains same as n.

Note: we will not touch the sorted array, Now we will pick second element of unsorted array and swap it the smallest element of remaining array, but don't do anything (swap or checking minimum) with sorted array. Now the size of sorted array becomes 2 and the size of unsorted array gets reduced by 2. And same process goes on.

#include<conio.h>
#include<stdlib.h>
#include<stdio.h>
void main()
{
    int n,i,j,temp,min;
    printf("enter the size of array: ");
    scanf("%d",&n);
    int a[n];
    printf("Enter the elements of array:\n");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);
    for(i=0;i<n-1;i++)
      {
          min=i;   
          for(j=i+1;j<n;j++)
            if(a[j]<a[min])
            min=j;
          if(min!=i)
          {
              temp=a[i];
              a[i]=a[min];
              a[min]=temp;
          }
      }
    printf("\ Sorted elements of array:\n");
    for(i=0;i<n;i++)
        printf("%d ",a[i]);
}

Comments

Popular posts from this blog

First_Come_First_Serve CPU Scheduling

Reversing stack Method 2 !! (One Helper Stack only)

Populating Next Right Pointers in Each Node in O(1) space (without queue and level order)

Calculate factorial of large numbers !! (Using Arrays)

Multiplication of large numbers (Given in string format)

Left View of Binary Tree (Method 1 using recursion)

Check Bracket Sequence

Image Multiplication

Boundary Traversal of binary tree

BST to greater sum tree