Algorithms_in_C  1.0.0
Set of algorithms implemented in C.
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. More...
 
void selectionSort (int *arr, int size)
 Selection sort algorithm implements. More...
 
static void test ()
 Test function. More...
 
int main (int argc, const char *argv[])
 Driver Code.
 

Detailed Description

Selection sort algorithm implementation.

Function Documentation

◆ 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 }
Here is the call graph for this function:

◆ 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 }
Here is the call graph for this function:
swap
void swap(int *first, int *second)
Swapped two numbers using pointer.
Definition: selection_sort.c:16
selectionSort
void selectionSort(int *arr, int size)
Selection sort algorithm implements.
Definition: selection_sort.c:28