w3resource

C Exercises: Selection sort algorithm

C Programming Searching and Sorting Algorithm: Exercise-1 with Solution

Write a C program to sort a list of elements using the selection sort algorithm.

According to Wikipedia "In computer science, selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) time complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort".

Note:
a) To find maximum of elements
b) To swap two elements

Pictorial presentation - Selection search algorithm:

C programming Selection sort algorithm

Sample Solution:

Sample C Code:

#include <stdio.h>
  int main()
  {
  int arr[10];
   int i, j, N, temp;
 /* function  declaration */
  int find_max(int  b[10], int k);
  void exchang(int  b[10], int k);
  printf("\nInput no. of values in the array : N");
  scanf("%d",&N);
   printf("\nInput the elements one by one: ");
  for(i=0; i<N ;  i++)
  {
  scanf("%d",&arr[i]);
  }
  /* Selection sorting  begins */
  exchang(arr,N);
  printf("Sorted  array :\n");
  for(i=0; i< N ;  i++)
  {
  printf("%d\n",arr[i]);
  }
}
/* function to find the maximum value */
  int find_max(int b[10], int k)
  {
  int max=0,j;
  for(j = 1; j <=  k; j++)
  {
  if ( b[j] >  b[max])
  {
  max =  j;
  }
  }
  return(max);
  }
  void exchang(int  b[10],int k)
  {
  int  temp, big, j;
  for ( j=k-1;  j>=1; j--)
  {
  big =  find_max(b,j);
  temp = b[big];
  b[big] = b[j];
  b[j] = temp;
  }
  return ;
  }

Sample Input:

Input no. of values in the array : 3
Input  the elements one by one: Sorted  array :15
 56
 12
 

Sample Output:

Input no. of values in the array : 
Input  the elements one by one: Sorted  array :
12
15
56

Flowchart:

Flowchart: C Programming - Selection sort

C Programming Code Editor:

Previous: C Searching and Sorting Algorithm Exercises Home.
Next: Write a C program to sort a list of elements using the bubble sort algorithm.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.