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

selection_sort.c: Add Selection Sort in C #163

Merged
merged 1 commit into from
Oct 17, 2018
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
35 changes: 35 additions & 0 deletions selection_sort/C/selection_sort.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#include <stdio.h> // 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;
}
}