Algorithms_in_C 1.0.0
Set of algorithms implemented in C.
Loading...
Searching...
No Matches
selection_sort.c File Reference

Selection sort algorithm implementation. More...

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
Include dependency graph for selection_sort.c:

Functions

void swap (int *first, int *second)
 Swapped two numbers using pointer.
 
void selectionSort (int *arr, int size)
 Selection sort algorithm implements.
 
static void test ()
 Test function.
 
int main (int argc, const char *argv[])
 Driver Code.
 

Detailed Description

Selection sort algorithm implementation.

Function Documentation

◆ main()

int main ( int  argc,
const char *  argv[] 
)

Driver Code.

70{
71 /* Intializes random number generator */
72 srand(time(NULL));
73 test();
74 return 0;
75}
static void test()
Test function.
Definition selection_sort.c:50
Here is the call graph for this function:

◆ selectionSort()

void selectionSort ( int *  arr,
int  size 
)

Selection sort algorithm implements.

Parameters
arrarray to be sorted
sizesize of array
29{
30 for (int i = 0; i < size - 1; i++)
31 {
32 int min_index = i;
33 for (int j = i + 1; j < size; j++)
34 {
35 if (arr[min_index] > arr[j])
36 {
37 min_index = j;
38 }
39 }
40 if (min_index != i)
41 {
42 swap(arr + i, arr + min_index);
43 }
44 }
45}

◆ swap()

void swap ( int *  first,
int *  second 
)

Swapped two numbers using pointer.

Parameters
firstfirst pointer of first number
secondsecond pointer of second number
17{
18 int temp = *first;
19 *first = *second;
20 *second = temp;
21}

◆ test()

static void test ( void  )
static

Test function.

Returns
None
51{
52 const int size = rand() % 500; /* random array size */
53 int *arr = (int *)calloc(size, sizeof(int));
54
55 /* generate size random numbers from -50 to 49 */
56 for (int i = 0; i < size; i++)
57 {
58 arr[i] = (rand() % 100) - 50; /* signed random numbers */
59 }
60 selectionSort(arr, size);
61 for (int i = 0; i < size - 1; ++i)
62 {
63 assert(arr[i] <= arr[i + 1]);
64 }
65 free(arr);
66}
#define free(ptr)
This macro replace the standard free function with free_dbg.
Definition malloc_dbg.h:26
#define calloc(elemCount, elemSize)
This macro replace the standard calloc function with calloc_dbg.
Definition malloc_dbg.h:22
void selectionSort(int *arr, int size)
Selection sort algorithm implements.
Definition selection_sort.c:28
Here is the call graph for this function: