[BAEL-3193] Bucket Sort In Java Code (#7731)

This commit is contained in:
Sam Millington 2019-09-07 05:31:51 +01:00 committed by Grzegorz Piwowarek
parent 1fc511ba7a
commit 648ef77f5d
3 changed files with 111 additions and 0 deletions

View File

@ -0,0 +1,70 @@
package com.baeldung.bucketsort;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class IntegerBucketSorter implements Sorter<Integer> {
private final Comparator<Integer> comparator;
public IntegerBucketSorter(Comparator<Integer> comparator) {
this.comparator = comparator;
}
public IntegerBucketSorter() {
comparator = Comparator.naturalOrder();
}
public List<Integer> sort(List<Integer> arrayToSort) {
List<List<Integer>> buckets = splitIntoUnsortedBuckets(arrayToSort);
for(List<Integer> bucket : buckets){
bucket.sort(comparator);
}
return concatenateSortedBuckets(buckets);
}
private List<Integer> concatenateSortedBuckets(List<List<Integer>> buckets){
List<Integer> sortedArray = new ArrayList<>();
int index = 0;
for(List<Integer> bucket : buckets){
for(int number : bucket){
sortedArray.add(index++, number);
}
}
return sortedArray;
}
private List<List<Integer>> splitIntoUnsortedBuckets(List<Integer> initialList){
final int[] codes = createHashes(initialList);
List<List<Integer>> buckets = new ArrayList<>(codes[1]);
for(int i = 0; i < codes[1]; i++) buckets.add(new ArrayList<>());
//distribute the data
for (int i : initialList) {
buckets.get(hash(i, codes)).add(i);
}
return buckets;
}
private int[] createHashes(List<Integer> input){
int m = input.get(0);
for (int i = 1; i < input.size(); i++) {
if (m < input.get(i)) {
m = input.get(i);
}
}
return new int[]{m, (int) Math.sqrt(input.size())};
}
private static int hash(int i, int[] code) {
return (int) ((double) i / code[0] * (code[1] - 1));
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.bucketsort;
import java.util.List;
public interface Sorter<T> {
List<T> sort(List<T> arrayToSort);
}

View File

@ -0,0 +1,33 @@
package com.baeldung.bucketsort;
import com.baeldung.bucketsort.IntegerBucketSorter;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class IntegerBucketSorterUnitTest {
private IntegerBucketSorter sorter;
@Before
public void setUp() throws Exception {
sorter = new IntegerBucketSorter();
}
@Test
public void givenUnsortedList_whenSortedUsingBucketSorter_checkSortingCorrect() {
List<Integer> unsorted = Arrays.asList(80,50,60,30,20,10,70,0,40,500,600,602,200,15);
List<Integer> expected = Arrays.asList(0,10,15,20,30,40,50,60,70,80,200,500,600,602);
List<Integer> actual = sorter.sort(unsorted);
assertEquals(expected, actual);
}
}