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; } }