Fix gnome algorithm

This commit is contained in:
edumoreira1506 2019-09-10 14:18:06 -03:00
parent e1b38711dd
commit 5d9f19b184

View File

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