Please visit, subscribe and share 10 Minutes Lectures in Computer Science

Sunday, 25 March 2018

Selection sort recursive program in C in Data structures

Selection sort recursive program in C in Data structures

Program in C:

#include <stdio.h>

int x[50]; //declaration of global variable for array
int selectionSort(int, int); //function declaration

int main()
int i, n = 0, total;
printf ("Enter the number of elements you like to sort : ");
scanf("%d", &total);

for (i=0;i<total;i++)
    printf("Enter the element %d: ", i+1);
    scanf("%d", &x[i]);

printf (" Array Elements before sorting: ");

for (i=0; i<total; i++)
    printf ("%d ", x[i]);

// call selection sort function by passing position and the total number of elements
selectionSort(n, total);

printf ("\n Array Elements after sorting: ");
for (i=0; i<total; i++)
    printf ("%d ", x[i]);

int selectionSort( int n, int total)
int k, temp, min_key, min_index;
if (n== total-1)
return (-1);
min_key = x[n]; //initially the value at index 0 is considered minimum

min_index = n;

for (k = n+1; k<total; k++)
 if (x[k] < min_key) //checks whether min_key is minimum or other element. If other element is minimum then the other element value will be stored as new min_key
  min_key = x[k];
  min_index = k;

temp = x[n]; // swaps x[n] and x[p]

x[n] = x[min_index];
x[min_index] = temp;
n++ ;
selectionSort(n, total); //recursive call of the function



Featured Content

Multiple choice questions in Natural Language Processing Home

MCQ in Natural Language Processing, Quiz questions with answers in NLP, Top interview questions in NLP with answers Multiple Choice Que...

All time most popular contents