diff --git a/README.md b/README.md index 9af71646..d3b51b1d 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ This repository contains examples of various algorithms written on different pro | [Heap Sort](https://en.wikipedia.org/wiki/Heapsort) | | | | [:octocat:](heap_sort/python) | | [Maximum Subarray Problem](https://en.wikipedia.org/wiki/Maximum_subarray_problem) | | | | [:octocat:](/maximum_subarray/Python)| | [Knapsack Problem](https://en.wikipedia.org/wiki/Knapsack_problem) | | | | [:octocat:](knapsack_problem/Python)| +| [Selecton Sort](https://en.wikipedia.org/wiki/Selection_sort) | [:octocat:](selection_sort/C) | | | | ## Implemented Data Structures diff --git a/selection_sort/C/selection_sort.c b/selection_sort/C/selection_sort.c new file mode 100644 index 00000000..5b5b0a62 --- /dev/null +++ b/selection_sort/C/selection_sort.c @@ -0,0 +1,35 @@ +#include // for printf function + +void selection_sort(int[], int); +void print_array(int[], int); + +int main() { + int arr[] = {4, 3, 42, 82, 5, 2, 33}; + int n = sizeof(arr) / sizeof(arr[0]); + selection_sort(arr, n); + printf("Sorted array is: "); + print_array(arr, n); + printf("\n"); + return 0; +} + +/* Function to print array */ +void print_array(int arr[], int n) { + for (int i = 0; i < n; ++i) { + printf("%d ", arr[i]); + } +} + +/* Selection Sort algorithm */ +void selection_sort(int arr[], int n) { + for (int i = 0; i < n - 1; ++i) { + int small = i; + for (int j = i + 1; j < n; ++j) { + if (arr[j] < arr[small]) + small = j; + } + int temp = arr[i]; + arr[i] = arr[small]; + arr[small] = temp; + } +}