Skip to content

Commit 2f362c9

Browse files
authored
Merge pull request TheAlgorithms#21 from KuLi/gnomeSort
Implemented gnome sort algorithm
2 parents 1d676b1 + 2b520fe commit 2f362c9

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

Sorts/gnomeSort.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
* Gnome sort is a sort algorithm that moving an element to its proper place is accomplished by a series of swap
3+
* more information: https://en.wikipedia.org/wiki/Gnome_sort
4+
*
5+
*/
6+
function gnomeSort(items) {
7+
8+
if (items.length <= 1) {
9+
10+
return;
11+
}
12+
13+
var i = 1;
14+
15+
while (i < items.length) {
16+
17+
if (items[i - 1] <= items[i]) {
18+
i++;
19+
} else {
20+
var temp = items[i];
21+
items[i] = items[i - 1];
22+
items[i - 1] = temp;
23+
24+
i = Math.max(1, i - 1);
25+
}
26+
}
27+
}
28+
29+
//Implementation of gnomeSort
30+
31+
var ar = [5, 6, 7, 8, 1, 2, 12, 14];
32+
//Array before Sort
33+
console.log(ar);
34+
gnomeSort(ar);
35+
//Array after sort
36+
console.log(ar);

0 commit comments

Comments
 (0)