File tree Expand file tree Collapse file tree 2 files changed +45
-0
lines changed
Expand file tree Collapse file tree 2 files changed +45
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff 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}
You can’t perform that action at this time.
0 commit comments