SIGN IN SIGN UP

Algorithms and Data Structures implemented in JavaScript for beginners, following best practices.

0 0 0 JavaScript
2017-09-30 20:15:17 +02:00
/*
* Gnome sort is a sort algorithm that moving an element to its proper place is accomplished by a series of swap
* more information: https://en.wikipedia.org/wiki/Gnome_sort
*
*/
export function gnomeSort(items) {
2020-05-03 09:05:12 +02:00
if (items.length <= 1) {
return
}
let i = 1
while (i < items.length) {
if (items[i - 1] <= items[i]) {
i++
} else {
;[items[i], items[i - 1]] = [items[i - 1], items[i]]
2020-05-03 09:05:12 +02:00
i = Math.max(1, i - 1)
2017-09-30 20:15:17 +02:00
}
2020-05-03 09:05:12 +02:00
}
return items
2017-09-30 20:15:17 +02:00
}
2020-05-03 09:05:12 +02:00
// Implementation of gnomeSort
2017-09-30 20:15:17 +02:00
// const ar = [5, 6, 7, 8, 1, 2, 12, 14]
// gnomeSort(ar)