Selection sort recursive program in C in Data structures

__Program in C:__
#include <stdio.h>

#include<conio.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]);

getch();

}

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

}

***********

Go to Sorting algorithms compared page

Go to Sorting algorithms and programs page

Go to Time complexity of sorting algorithms page

## No comments:

## Post a Comment