Skip to content

Commit c4597f3

Browse files
committed
Add AmericanFlagSort algorithm
- Implements American Flag Sort using bucket-based radix sort approach - Includes comprehensive test suite extending SortingAlgorithmTest - Follows project coding standards and documentation style
1 parent 9484c7e commit c4597f3

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package com.thealgorithms.sorts;
2+
3+
/**
4+
* American Flag Sort Algorithm Implementation
5+
*
6+
* @see <a href="https://en.wikipedia.org/wiki/American_flag_sort">American Flag Sort Algorithm</a>
7+
*/
8+
public class AmericanFlagSort implements SortAlgorithm {
9+
10+
@Override
11+
public <T extends Comparable<T>> T[] sort(T[] array) {
12+
if (array == null || array.length <= 1) {
13+
return array;
14+
}
15+
americanFlagSort(array, 0, array.length - 1, 0);
16+
return array;
17+
}
18+
19+
private <T extends Comparable<T>> void americanFlagSort(T[] array, int start, int end, int digitIndex) {
20+
if (start >= end || digitIndex < 0) {
21+
return;
22+
}
23+
24+
int[] count = new int[256];
25+
int[] offset = new int[256];
26+
27+
for (int i = start; i <= end; i++) {
28+
int digit = getDigit(array[i], digitIndex);
29+
count[digit]++;
30+
}
31+
32+
offset[0] = start;
33+
for (int i = 1; i < 256; i++) {
34+
offset[i] = offset[i - 1] + count[i - 1];
35+
}
36+
37+
for (int bucket = 0; bucket < 256; bucket++) {
38+
while (count[bucket] > 0) {
39+
int origin = offset[bucket];
40+
int digit = getDigit(array[origin], digitIndex);
41+
SortUtils.swap(array, origin, offset[digit]);
42+
offset[digit]++;
43+
count[digit]--;
44+
}
45+
}
46+
47+
for (int bucket = 0; bucket < 256; bucket++) {
48+
int bucketStart = (bucket == 0) ? start : offset[bucket - 1];
49+
int bucketEnd = offset[bucket] - 1;
50+
if (bucketStart < bucketEnd) {
51+
americanFlagSort(array, bucketStart, bucketEnd, digitIndex - 1);
52+
}
53+
}
54+
}
55+
56+
private <T extends Comparable<T>> int getDigit(T element, int digitIndex) {
57+
String str = element.toString();
58+
if (digitIndex >= str.length()) {
59+
return 0;
60+
}
61+
return str.charAt(str.length() - 1 - digitIndex);
62+
}
63+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package com.thealgorithms.sorts;
2+
3+
public class AmericanFlagSortTest extends SortingAlgorithmTest {
4+
@Override
5+
SortAlgorithm getSortAlgorithm() {
6+
return new AmericanFlagSort();
7+
}
8+
}

0 commit comments

Comments
 (0)