Skip to content

Instantly share code, notes, and snippets.

@AdrianSkar
Created May 9, 2024 16:30
Show Gist options
  • Save AdrianSkar/8d0097cc57ad7103004e2a69cf7725ee to your computer and use it in GitHub Desktop.
Save AdrianSkar/8d0097cc57ad7103004e2a69cf7725ee to your computer and use it in GitHub Desktop.
selection sort in C
# include <stdio.h>
// selection sort example
void ft_ssort_arr(int *arr, int size)
{
int i = 0, j; // arr indexes
int min; // index of the minimum value
int temp; // temporary variable to store the value of the array
while (i < size-1) // arr iter
{
//| print arr
//for (int k = 0; k < size; k++)
// printf("%d ", arr[k]);
//printf("\n");
min = i; // min
j = i + 1; // i + 1 (next for compare)
while (j < size) // rest of arr iter
{
if (arr[j] < arr[min]) // find min
min = j;
j++;
}
if (min != i) // if curr idx is not the min
{ // swap them
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
//printf("Swapping %d with %d\n", arr[i], arr[min]);
}
i++;
}
}
int main (void)
{
int arr[] = {5,2,1,3,6,4};
int size = sizeof(arr) / sizeof(arr[0]); // arr size / size of one element
ft_ssort_arr(arr, size);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment