Skip to content

Instantly share code, notes, and snippets.

@Per48edjes
Last active May 26, 2022 20:21
Show Gist options
  • Save Per48edjes/07438e639fc5a79320a71be23aa4c01a to your computer and use it in GitHub Desktop.
Save Per48edjes/07438e639fc5a79320a71be23aa4c01a to your computer and use it in GitHub Desktop.
Implementation of selection sort on array of integers in C
#include <stdio.h>
void swap(int *a, int *b);
void print_array(int *arr, int len_arr);
int main(void)
{
int items[] = { 5, 2, 7, 4, 1, 6, 3, 0 };
int len_items = sizeof(items) / sizeof(*items);
// Print original order
print_array(items, len_items);
// Selection sort
for (int i = 0; i < len_items; ++i)
{
int *smallest_number = &items[i];
for (int j = i + 1; j < len_items; j++)
{
if (items[j] < *smallest_number)
{
smallest_number = &items[j];
}
}
swap(&items[i], smallest_number);
}
// Print sorted order
print_array(items, len_items);
return 0;
}
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
void print_array(int *arr, int len_arr)
{
for (int i = 0; i < len_arr; ++i)
{
printf("%d ", arr[i]);
if (len_arr - 1 == i)
{
printf("\n");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment