From e4639ebdedcb81706636b4b4938e64c728b9e0a2 Mon Sep 17 00:00:00 2001 From: yashasingh Date: Tue, 30 Oct 2018 02:48:51 +0530 Subject: [PATCH] selection_sort.cpp: Add cpp selection sort Implementation of Cpp selection sort for NITSkmOS/Algorithms. closes https://github.com/NITSkmOS/Algorithms/issues/482 --- README.md | 2 +- selection_sort/Cpp/selection_sort.cpp | 28 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 selection_sort/Cpp/selection_sort.cpp diff --git a/README.md b/README.md index bd3e5bfa..d8f56d17 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,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) | | | | +| [Selecton Sort](https://en.wikipedia.org/wiki/Selection_sort) | [:octocat:](selection_sort/C) | [:octocat:](selection_sort/Cpp) | | | ## Implemented Data Structures diff --git a/selection_sort/Cpp/selection_sort.cpp b/selection_sort/Cpp/selection_sort.cpp new file mode 100644 index 00000000..3ce2f692 --- /dev/null +++ b/selection_sort/Cpp/selection_sort.cpp @@ -0,0 +1,28 @@ +#include +using namespace std; + +void selection_sort(int[], int); + +int main() { + int n = 10, arr[] = {5, 7, 9, 8, 3, 1, 4, 2, 10, 6}; + selection_sort(arr, n); + cout << "Sorted array after selection sort algorithm- "; + for(int i = 0; i < n; i++) { + cout << arr[i] << " "; + } + cout << endl; + return 0; +} + +void selection_sort(int arr[], int n) { + //This function implements the main selection sort algorithm. + int i, j, temp; + for(i = 0; i < n; i++) + for(j = i+1; j < n; j++) { + if(arr[i] > arr[j]) { + temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } +}