C Fundamentals
Algorithms · data structures · cryptography · systems — pure C11, zero deps
Loading...
Searching...
No Matches
selection_sort.c
Go to the documentation of this file.
1/**
2 * @file selection_sort.c
3 * @brief Implementation of selection sort algorithm
4 *
5 * Selection sort works by repeatedly finding the minimum element
6 * from the unsorted portion and placing it at the beginning.
7 */
8
9#include "sorts.h"
10#include <string.h>
11
12size_t find_min_index(char **arr, size_t start, size_t n) {
13 size_t min_idx = start;
14
15 for (size_t j = start + 1; j < n; j++) {
16 if (strcmp(arr[j], arr[min_idx]) < 0) {
17 min_idx = j;
18 }
19 }
20
21 return min_idx;
22}
23
24void selection_sort_strings(char **arr, size_t n) {
25 if (n <= 1)
26 return;
27
28 for (size_t i = 0; i < n - 1; i++) {
29 // Find the minimum element in unsorted portion
30 size_t min_idx = find_min_index(arr, i, n);
31
32 // Swap with the first unsorted element
33 if (min_idx != i) {
34 char *temp = arr[i];
35 arr[i] = arr[min_idx];
36 arr[min_idx] = temp;
37 }
38 }
39}
40
41void selection_sort_ints(int *arr, size_t n) {
42 if (n <= 1)
43 return;
44
45 for (size_t i = 0; i < n - 1; i++) {
46 size_t min_idx = i;
47
48 for (size_t j = i + 1; j < n; j++) {
49 if (arr[j] < arr[min_idx]) {
50 min_idx = j;
51 }
52 }
53
54 if (min_idx != i) {
55 int temp = arr[i];
56 arr[i] = arr[min_idx];
57 arr[min_idx] = temp;
58 }
59 }
60}
void selection_sort_ints(int *arr, size_t n)
size_t find_min_index(char **arr, size_t start, size_t n)
void selection_sort_strings(char **arr, size_t n)
Unified header for all sorting algorithms.