TheAlgorithms-C/sorting/selection_sort.c

76 lines
1.5 KiB
C
Raw Normal View History

/**
* @file
* @brief [Selection sort](https://en.wikipedia.org/wiki/Selection_sort)
* algorithm implementation.
*/
#include <assert.h>
2018-11-08 10:04:04 +03:00
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
2018-11-08 10:04:04 +03:00
/**
* Swapped two numbers using pointer
* @param first first pointer of first number
* @param second second pointer of second number
*/
void swap(int *first, int *second)
{
2018-11-08 10:04:04 +03:00
int temp = *first;
*first = *second;
*second = temp;
}
/**
* Selection sort algorithm implements
* @param arr array to be sorted
* @param size size of array
2018-11-08 10:04:04 +03:00
*/
void selectionSort(int *arr, int size)
{
for (int i = 0; i < size - 1; i++)
{
2018-11-08 10:04:04 +03:00
int min_index = i;
for (int j = i + 1; j < size; j++)
{
if (arr[min_index] > arr[j])
{
2018-11-08 10:04:04 +03:00
min_index = j;
}
}
if (min_index != i)
{
swap(arr + i, arr + min_index);
}
2018-11-08 10:04:04 +03:00
}
}
/** Test function
* @returns None
*/
static void test()
{
const int size = rand() % 500; /* random array size */
int *arr = (int *)calloc(size, sizeof(int));
/* generate size random numbers from -50 to 49 */
for (int i = 0; i < size; i++)
{
arr[i] = (rand() % 100) - 50; /* signed random numbers */
}
selectionSort(arr, size);
for (int i = 0; i < size - 1; ++i)
{
assert(arr[i] <= arr[i + 1]);
2018-11-08 10:04:04 +03:00
}
free(arr);
}
/** Driver Code */
int main(int argc, const char *argv[])
{
/* Intializes random number generator */
srand(time(NULL));
test();
2018-11-08 10:04:04 +03:00
return 0;
}