From 2a5e03a8d620ea63a5a7033bdc3e62c630d0fc29 Mon Sep 17 00:00:00 2001 From: Vivek R <123vivekr@gmail.com> Date: Tue, 2 Oct 2018 18:26:54 +0530 Subject: [PATCH] selection_sort.c: Add Selection Sort in C This adds Selection Sort algorithm written in C Closes https://github.com/NITSkmOS/Algorithms/issues/145 --- README.md | 2 +- selection_sort/C/selection_sort.c | 35 +++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 selection_sort/C/selection_sort.c diff --git a/README.md b/README.md index de6386f3..f26d92b9 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ This repository contains examples of various algorithms written on different pro | [Binary Search](https://en.wikipedia.org/wiki/Binary_search_algorithm) | | [:octocat:](binary_search/Cpp) | | [:octocat:](binary_search/Python) | | [Bubble Sort](https://en.wikipedia.org/wiki/Bubble_sort) | [:octocat:](bubble_sort/C) | [:octocat:](bubble_sort/Cpp) | | | | [Shell Sort](https://en.wikipedia.org/wiki/Shellsort) | | | | [:octocat:](shell_sort/Python) | - +| [Selection 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..48329137 --- /dev/null +++ b/selection_sort/C/selection_sort.c @@ -0,0 +1,35 @@ +#include + +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; ++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; + } +}