Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Wednesday, 27 March 2019

Selection Sort Algorithm


ALGORITHM SelectionSort(A[0..n 1])

//Sorts a given array by selection sort
//Input: An array 
A[0..1] of orderable elements
//Output: Array 
A[0..1] sorted in nondecreasing orderfor ← to domin ← ifor ← to do
if 
A[j< A[minmin ← jswap A[i] and A[min]  



C program:



#include <stdio.h>
#include<stdlib.h>
  int main ()
{
  int i, j, a[20], n, min, temp;
  printf ("ENTER SIZE OF ARRAY\n");
  scanf ("%d", &n);
  printf ("enter  elements\n");
  for (i = 0; i < n; i++)
    scanf ("%d", &a[i]);
  for (i = 0; i <= n - 2; i++)
    {
      min = i;
      for (j = i + 1; j <= n - 1; j++)
        {
          if (a[j] < a[min])
            min = j;
        }
      temp = a[i];
      a[i] = a[min];
      a[min] = temp;
    }
  printf ("SORTED ELEMENTS ARE:\n");
  for (i = 0; i < n; i++)
    printf ("%d\t", a[i]);


  return 0;
}


Output:

ENTER SIZE OF ARRAY
10
enter  elements
2
3
4
5
2
6
78
9
1
0
SORTED ELEMENTS ARE:
0       1       2       2       3       4       5       6       9       78

0 comments:

Post a Comment