Skip to content

Commit 2b520fe

Browse files
committed
Implemented gnome sort algorithm
1 parent cedbe13 commit 2b520fe

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

Sorts/gnomeSort.js

+36
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)