Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added selection sort algorithm in c #48

Merged
merged 5 commits into from
Oct 8, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions C/Algorithms/Sorting/selectionSort.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
Author : Shaleen Badola
Date : 07/10/2021
Description : Selection sort algorithm in c
*/

/*
Consider N = number of elements in the array
Time Complexity : O(N^2)
Space Complexity : O(N)
*/


#include <stdio.h>

// Funtion for selection sort
void selection(int arr[], int n) {
int small;

for (int i = 0; i < n - 1; i++) {
small = i;

// find the next smallest element index
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[small]) {
small = j;
}
}

// swap the current element to the next smallest element
int temp = arr[small];
arr[small] = arr[i];
arr[i] = temp;
}
}

// Function to print the array
void printArr(int a[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", a[i]);
}
}

int main() {
int a[] = { 12, 31, 25, 8, 32, 17 };

int n = sizeof(a) / sizeof(a[0]);

printf("Before sorting array elements are - \n");
printArr(a, n);

// Calling selection sort
selection(a, n);

printf("\nAfter sorting array elements are - \n");
printArr(a, n);

return 0;
}