chore(C): add selection sort (#399)

pull/407/head
Sri Subathra Devi B 2021-07-30 19:16:05 +05:30 committed by GitHub
parent f01e030335
commit dcdf04876b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 42 additions and 0 deletions

View File

@ -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)

View File

@ -0,0 +1,41 @@
#include <stdio.h>
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;i<n-1;i++){
for (j=i+1;j<n;j++){
if(a[i]>a[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;
}