From dcdf04876bf9e74cd6160f43ec32a9602f99a31d Mon Sep 17 00:00:00 2001 From: Sri Subathra Devi B Date: Fri, 30 Jul 2021 19:16:05 +0530 Subject: [PATCH] chore(C): add selection sort (#399) --- algorithms/C/README.md | 1 + algorithms/C/sorting/selection-sort.c | 41 +++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 algorithms/C/sorting/selection-sort.c diff --git a/algorithms/C/README.md b/algorithms/C/README.md index 2d00b6e0..c304319f 100644 --- a/algorithms/C/README.md +++ b/algorithms/C/README.md @@ -27,6 +27,7 @@ - [Merge Sort](sorting/merge-sort.c) - [Insertion Sort](sorting/insertion-sort.c) - [Heap Sort](sorting/heap-sort.c) +- [Selection Sort](sorting/selection-sort.c) ## Strings - [Count Words](strings/count-words.c) diff --git a/algorithms/C/sorting/selection-sort.c b/algorithms/C/sorting/selection-sort.c new file mode 100644 index 00000000..ea0516fd --- /dev/null +++ b/algorithms/C/sorting/selection-sort.c @@ -0,0 +1,41 @@ + +#include + +void swap(int *x, int *y) +{ + int t = *x; + *x = *y; + *y = t; +} + +void selectionSort(int a[], int n) +{ + int i, j; + for (i=0;ia[j]){ + swap(&a[i], &a[j]); + } + } + } +} + +void printArray(int a[], int size) +{ + int i; + for (i=0; i < size; i++){ + printf("%d ", a[i]); + } +} + +int main() +{ + int a[] = {64, 25, 25, 12, 22, 11, 90}; + int n = sizeof(a)/sizeof(a[0]); + printf("Initial array: \n"); + printArray(a, n); + selectionSort(a, n); + printf("\nSorted array: \n"); + printArray(a, n); + return 0; +}