Skip to content

Commit 45219c1

Browse files
committed
feat(sorts): add TournamentSort (winner-tree) [#6631]
1 parent 1437036 commit 45219c1

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
package com.thealgorithms.sorts;
2+
import java.util.Arrays;
3+
4+
/**
5+
* Tournament Sort (Winner Tree) – comparison-based sorting that repeatedly
6+
* selects the minimum via a "winner tree" and removes it,
7+
* updating winners along the path.
8+
*
9+
* Time: O(n log m) where m is next power-of-two ≥ n
10+
*/
11+
public final class TournamentSort {
12+
13+
private TournamentSort() {
14+
}
15+
16+
public static <T extends Comparable<T>> void sort(T[] a) {
17+
if (a == null || a.length < 2) return;
18+
19+
final int n = a.length;
20+
int m = 1;
21+
while (m < n) m <<= 1;
22+
23+
// Winner-tree nodes;
24+
Node<T>[] tree = new Node[2 * m];
25+
26+
for (int i = 0; i < n; i++) {
27+
int leafPos = m + i;
28+
tree[leafPos] = new Node<>(a[i], leafPos);
29+
}
30+
31+
for (int i = m - 1; i >= 1; i--) {
32+
tree[i] = minNode(tree[2 * i], tree[2 * i + 1]);
33+
}
34+
35+
T[] out = Arrays.copyOf(a, n);
36+
for (int k = 0; k < n; k++) {
37+
Node<T> winner = tree[1];
38+
out[k] = winner.value;
39+
40+
// remove winner leaf by setting it to null (acts like +∞)
41+
int pos = winner.leafPos;
42+
tree[pos] = null;
43+
44+
// re-compute winners up the path
45+
pos >>= 1;
46+
while (pos >= 1) {
47+
tree[pos] = minNode(tree[2 * pos], tree[2 * pos + 1]);
48+
pos >>= 1;
49+
}
50+
}
51+
52+
System.arraycopy(out, 0, a, 0, n);
53+
}
54+
55+
public static void sort(int[] a) {
56+
if (a == null || a.length < 2) return;
57+
Integer[] boxed = new Integer[a.length];
58+
for (int i = 0; i < a.length; i++) boxed[i] = a[i];
59+
sort(boxed);
60+
for (int i = 0; i < a.length; i++) a[i] = boxed[i];
61+
}
62+
63+
private static <T extends Comparable<T>> Node<T> minNode(Node<T> left, Node<T> right) {
64+
if (left == null) return right;
65+
if (right == null) return left;
66+
return (left.value.compareTo(right.value) <= 0) ? left : right;
67+
}
68+
69+
private static final class Node<T extends Comparable<T>> {
70+
final T value;
71+
final int leafPos;
72+
Node(T v, int p) {
73+
this.value = v;
74+
this.leafPos = p;
75+
}
76+
}
77+
}

0 commit comments

Comments
 (0)