From 5d9f19b184ec956f7b735d84eab7232d6b5de6bc Mon Sep 17 00:00:00 2001 From: edumoreira1506 Date: Tue, 10 Sep 2019 14:18:06 -0300 Subject: [PATCH] Fix gnome algorithm --- src/algorithms/sorting/gnome-sort/GnomeSort.js | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/algorithms/sorting/gnome-sort/GnomeSort.js b/src/algorithms/sorting/gnome-sort/GnomeSort.js index 4c2a700c..ac0bdd1f 100644 --- a/src/algorithms/sorting/gnome-sort/GnomeSort.js +++ b/src/algorithms/sorting/gnome-sort/GnomeSort.js @@ -5,25 +5,30 @@ export default class GnomeSort extends Sort { * @param {number[]} originalArray */ sort(originalArray) { - const sortedArray = originalArray; + const sortedArray = originalArray.map(element => element); // Variable that will be itering during loop let index = 0; + if (sortedArray.length <= 1) { + return sortedArray; + } + // Loop for sort the array - while (index < originalArray.length) { + while (index < sortedArray.length) { // Detects the first iteration if (index === 0) { index += 1; } // Detects if the current position is smaller of previous - if (originalArray[index] >= originalArray[index - 1]) { + if (sortedArray[index] >= sortedArray[index - 1]) { index += 1; } else { // Change the position of current position for before - sortedArray[index] = originalArray[index - 1]; - sortedArray[index - 1] = originalArray[index]; + const temp = sortedArray[index]; + sortedArray[index] = sortedArray[index - 1]; + sortedArray[index - 1] = temp; index -= 1; } }