Wednesday 16 January 2019

write a program to implement selection sort in c

Hello friends,  selection sort is one of the sorting method, in this method we select first number and compare with second number, if second number is smaller than first number than swap both the number, if second number is larger, than it moves to next position, this method is repeat until reach last position


Ex:

selection sort :


4 2 5 7 9                It's a given number

4<->2 5 7 9            4 and 2 is compare if   2<4-->"true" than swap.

2 4 <->5 7 9          compare with next two position if 5<4-->"False"   

2 4 5 7 9

2 4 5 <->7 9     (7<5)-->False

2 4 5 7 9 

2 4 5 7 <->9   (9<7)-->False

Round two begins until sorting.

 implement selection sort in c :

#include <stdio.h>
int main()
{
  int a[100], n, i, j, position, swap;
  printf("Enter number of elements\n");
  scanf("%d", &n);
  printf("Enter %d integers\n", n);
  for (i = 0; i < n; i++)
    scanf("%d", &array[c]);
  for (i = 0; i < (n - 1); i++)
  {
    position = i;
   
    for (j = j + 1; j < n; j++)
    {
      if (array[position] > array[d])
        position = j;
    }
    if (position != c)
    {
      swap = a[i];
      a[i] = a[position];
      a[position] = swap;
    }
  }
  printf("Sorted list in ascending order:\n");

  for (i = 0; i < n; i++)
    printf("%d\n", a[c]);
  return 0;
}


Output Window:




Download Executable .c file click below link

 Download

No comments:

Post a Comment