Skip to content

Commit aac3819

Browse files
committed
Added Gnome Sort implementation and test for it
1 parent 7319de0 commit aac3819

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package ru.algorithms;
2+
3+
import ru.utils.SortingUtils;
4+
5+
/**
6+
* Implementation of "Gnome (Stupid) sort" algorithm.
7+
* Worst time: 0(n^2)
8+
* Average time: 0(n^2)
9+
* Best time: 0(n)
10+
* <p>
11+
* Memory cost: 0(1)
12+
*
13+
* @param <T> Data type of array elements
14+
*/
15+
public class GnomeSort<T extends Comparable<? super T>> implements Sorter<T> {
16+
17+
/**
18+
* 1. If the current array element is larger or equal to the previous array element then go one step right;
19+
* 2. If the current array element is smaller than the previous array element then swap these two elements and
20+
* go one step backwards;
21+
* 3. Repeat steps 1 and 2 while current index < array length
22+
*
23+
* @param array array for sorting
24+
*/
25+
@Override
26+
public void sort(T[] array) {
27+
int currIndex = 1;
28+
while(currIndex < array.length) {
29+
if (array[currIndex - 1].compareTo(array[currIndex]) > 0) {
30+
SortingUtils.swap(array, currIndex - 1, currIndex);
31+
currIndex--;
32+
}
33+
else
34+
currIndex++;
35+
if (currIndex == 0)
36+
currIndex++;
37+
}
38+
}
39+
}

src/test/java/ru/TestAlgorithms.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,4 +141,10 @@ void testCycleSort() {
141141
sortTest(new CycleSort<>());
142142
}
143143

144+
@Test
145+
@DisplayName("Gnome Sort test")
146+
void testGnomeSort() {
147+
sortTest(new GnomeSort<>());
148+
}
149+
144150
}

0 commit comments

Comments
 (0)