From 09a8115325e227eefef31783d85da9b8d1ae2451 Mon Sep 17 00:00:00 2001 From: Kevin Nguyen Date: Thu, 16 Jun 2016 10:10:02 -0700 Subject: [PATCH] code for chapter 2 in javascript --- .../javascript/01_selection_sort.js | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 02_selection_sort/javascript/01_selection_sort.js diff --git a/02_selection_sort/javascript/01_selection_sort.js b/02_selection_sort/javascript/01_selection_sort.js new file mode 100644 index 00000000..1ece0bee --- /dev/null +++ b/02_selection_sort/javascript/01_selection_sort.js @@ -0,0 +1,27 @@ +'use strict'; + +// Finds the smallest value in an array +function findSmallest(arr) { + let smallest = arr[0]; // Stores the smallest value + let smallest_index = 0; // Stores the index of the smallest value + for (let i = 1; i < arr.length; i++) { + if (arr[i] < smallest) { + smallest = arr[i]; + smallest_index = i; + } + } + return smallest_index; +} + +// Sort array +function selectionSort(arr) { + const newArr = []; + for (let i = 0, length = arr.length; i < length; i++) { + // Finds the smallest element in the array and adds it to the new array + let smallest = findSmallest(arr); + newArr.push(arr.splice(smallest, 1)[0]); + } + return newArr; +} + +console.log(selectionSort([5, 3, 6, 2, 10])); // [2, 3, 5, 6, 10]