2020-07-31 05:04:22 +03:00
|
|
|
/**
|
|
|
|
* @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>
|
2020-04-24 03:45:45 +03:00
|
|
|
#include <stdlib.h>
|
2020-07-31 05:04:22 +03:00
|
|
|
#include <time.h>
|
2018-11-08 10:04:04 +03:00
|
|
|
|
2020-07-31 05:04:22 +03:00
|
|
|
/**
|
|
|
|
* Swapped two numbers using pointer
|
|
|
|
* @param first first pointer of first number
|
|
|
|
* @param second second pointer of second number
|
|
|
|
*/
|
2020-04-24 03:45:45 +03:00
|
|
|
void swap(int *first, int *second)
|
|
|
|
{
|
2018-11-08 10:04:04 +03:00
|
|
|
int temp = *first;
|
|
|
|
*first = *second;
|
|
|
|
*second = temp;
|
|
|
|
}
|
|
|
|
|
2020-07-31 05:04:22 +03:00
|
|
|
/**
|
|
|
|
* Selection sort algorithm implements
|
|
|
|
* @param arr array to be sorted
|
|
|
|
* @param size size of array
|
2018-11-08 10:04:04 +03:00
|
|
|
*/
|
2020-04-24 03:45:45 +03:00
|
|
|
void selectionSort(int *arr, int size)
|
|
|
|
{
|
2020-07-31 05:04:22 +03:00
|
|
|
for (int i = 0; i < size - 1; i++)
|
2020-04-24 03:45:45 +03:00
|
|
|
{
|
2018-11-08 10:04:04 +03:00
|
|
|
int min_index = i;
|
2020-04-24 03:45:45 +03:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
}
|
2020-07-31 05:04:22 +03:00
|
|
|
if (min_index != i)
|
|
|
|
{
|
|
|
|
swap(arr + i, arr + min_index);
|
|
|
|
}
|
2018-11-08 10:04:04 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-31 05:04:22 +03:00
|
|
|
/** Test function
|
|
|
|
* @returns None
|
|
|
|
*/
|
|
|
|
static void test()
|
2020-04-24 03:45:45 +03:00
|
|
|
{
|
2020-07-31 05:04:22 +03:00
|
|
|
const int size = rand() % 500; /* random array size */
|
|
|
|
int *arr = (int *)calloc(size, sizeof(int));
|
2020-04-24 03:45:45 +03:00
|
|
|
|
2020-07-31 05:04:22 +03:00
|
|
|
/* generate size random numbers from -50 to 49 */
|
|
|
|
for (int i = 0; i < size; i++)
|
2020-04-24 03:45:45 +03:00
|
|
|
{
|
2020-07-31 05:04:22 +03:00
|
|
|
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
|
|
|
}
|
2020-04-24 03:45:45 +03:00
|
|
|
free(arr);
|
2020-07-31 05:04:22 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
/** 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;
|
|
|
|
}
|