File tree Expand file tree Collapse file tree 2 files changed +47
-0
lines changed
Expand file tree Collapse file tree 2 files changed +47
-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 "Odd-even 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 OddEvenSort <T extends Comparable <? super T >> implements Sorter <T > {
16+
17+ /**
18+ * In the odd phase, we perform a bubble sort on odd indexed elements and in the even phase,
19+ * we perform a bubble sort on even indexed elements.
20+ *
21+ * @param array array for sorting
22+ */
23+ @ Override
24+ public void sort (T [] array ) {
25+ boolean isSorted ;
26+ do {
27+ isSorted = true ;
28+ for (int i = 1 ; i < array .length - 2 ; i += 2 )
29+ if (array [i ].compareTo (array [i + 1 ]) > 0 ) {
30+ SortingUtils .swap (array , i , i + 1 );
31+ isSorted = false ;
32+ }
33+ for (int i = 0 ; i < array .length - 2 ; i += 2 )
34+ if (array [i ].compareTo (array [i + 1 ]) > 0 ) {
35+ SortingUtils .swap (array , i , i + 1 );
36+ isSorted = false ;
37+ }
38+ } while (!isSorted );
39+ }
40+
41+ }
Original file line number Diff line number Diff line change @@ -111,4 +111,10 @@ void testInsertionSort() {
111111 sortTest (new InsertionSort <>());
112112 }
113113
114+ @ Test
115+ @ DisplayName ("Odd-even Sort test" )
116+ void testOddEvenSort () {
117+ sortTest (new OddEvenSort <>());
118+ }
119+
114120}
You can’t perform that action at this time.
0 commit comments