TheAlgorithms-C/sorting/selection_sort_recursive.c

104 lines
2.1 KiB
C
Raw Normal View History

2021-02-24 11:24:57 +03:00
/**
* @file
2021-02-24 21:42:15 +03:00
* @author [Dhruv Pasricha](https://github.com/DhruvPasricha)
2021-02-24 11:24:57 +03:00
* @brief [Selection Sort](https://en.wikipedia.org/wiki/Selection_sort)
* implementation using recursion.
*/
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/**
* @brief Swapped two numbers using pointer
* @param first pointer of first number
* @param second pointer of second number
2021-02-24 11:24:57 +03:00
*/
void swap(int *first, int *second)
{
int temp = *first;
*first = *second;
*second = temp;
}
/**
* @brief Returns the index having minimum value using recursion
* @param arr array to be sorted
2021-02-24 11:24:57 +03:00
* @param size size of array
* @return min_index index of element having minimum value.
2021-02-24 11:24:57 +03:00
*/
int findIndex(const int *arr, const int size)
2021-02-24 11:24:57 +03:00
{
if (size == 1)
{
return 0;
}
// marking recursive call to reach starting element
int min_index = findIndex(arr, size - 1);
if (arr[size - 1] < arr[min_index])
{
min_index = size - 1;
}
return min_index;
}
/**
* @brief Selection Sort algorithm implemented using recursion
2021-02-24 11:24:57 +03:00
* @param arr array to be sorted
* @param size size of the array
* @returns void
2021-02-24 11:24:57 +03:00
*/
void selectionSort(int *arr, const int size)
2021-02-24 11:24:57 +03:00
{
if (size == 1)
{
return;
}
/* findIndex(arr, size) returned the index having min value*/
int min_index = findIndex(arr, size);
/* arr[min_index] is the minimum value in the array*/
if (min_index != 0)
{
swap(&arr[0], &arr[min_index]);
}
/*sorted the remaining array recursively*/
selectionSort(arr + 1, size - 1);
}
/**
* Test function
*/
void test()
{
const int size = 10;
int *arr = (int *)calloc(size, sizeof(int));
/* generate size random numbers from 0 to 100 */
for (int i = 0; i < size; i++)
{
arr[i] = rand() % 100;
}
selectionSort(arr, size);
for (int i = 0; i < size - 1; ++i)
{
assert(arr[i] <= arr[i + 1]);
}
free(arr);
}
/** Driver Code */
int main()
{
/* Intializes random number generator */
srand(time(NULL));
test(); // run self-test implementations
2021-02-24 11:24:57 +03:00
return 0;
}