mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-11-10 11:09:43 +08:00
Fix gnome algorithm
This commit is contained in:
parent
e1b38711dd
commit
5d9f19b184
@ -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;
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user