From 9f47a50f33707d045606ae90e78790cc29eeceff Mon Sep 17 00:00:00 2001 From: volatiana Date: Fri, 25 Sep 2020 18:33:22 +0300 Subject: [PATCH] create selection sort --- Sorts/SelectionSort.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Sorts/SelectionSort.js diff --git a/Sorts/SelectionSort.js b/Sorts/SelectionSort.js new file mode 100644 index 0000000..9170e6f --- /dev/null +++ b/Sorts/SelectionSort.js @@ -0,0 +1,24 @@ +export default SelectionSort = function (arr) { + let n = arr.length; + + for (let i = 0; i < n; i++) { + // Set the minimum to this position. + min_index = i; + + // Looking for a smaller number in the unsorted subarray. + for (let j = i + 1; j < n; j++) { + // If find one, set the minimum to this position. + if (arr[j] < arr[min_index]) { + min_index = j; + } + } + + // If the current minimum index is not the minimum index you started with, swap the elements. + if (min_index != i) { + let temp = arr[i]; + arr[i] = arr[min_index]; + arr[min_index] = temp; + } + } + return arr; +};