Skip to content

Commit 1c6b7dc

Browse files
committed
Added Odd-even Sort implementation and test for it
1 parent 2442e45 commit 1c6b7dc

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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+
}

src/test/java/ru/TestAlgorithms.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff 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
}

0 commit comments

Comments
 (0)