[BAEL-3193] - changes made to clean up code (#7760)

* [BAEL-3193] - changes made to clean up code

* Fixed missing linkedList import

* [BAEL-3193] - changing the default value in the findMax function
This commit is contained in:
Sam Millington 2019-09-17 15:03:20 +01:00 committed by Grzegorz Piwowarek
parent 8da0c75aef
commit 76c48c308e
3 changed files with 16 additions and 18 deletions

View File

@ -2,6 +2,7 @@ package com.baeldung.bucketsort;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.LinkedList;
import java.util.List; import java.util.List;
public class IntegerBucketSorter implements Sorter<Integer> { public class IntegerBucketSorter implements Sorter<Integer> {
@ -28,43 +29,40 @@ public class IntegerBucketSorter implements Sorter<Integer> {
} }
private List<Integer> concatenateSortedBuckets(List<List<Integer>> buckets){ private List<Integer> concatenateSortedBuckets(List<List<Integer>> buckets){
List<Integer> sortedArray = new ArrayList<>(); List<Integer> sortedArray = new LinkedList<>();
int index = 0;
for(List<Integer> bucket : buckets){ for(List<Integer> bucket : buckets){
for(int number : bucket){ sortedArray.addAll(bucket);
sortedArray.add(index++, number);
}
} }
return sortedArray; return sortedArray;
} }
private List<List<Integer>> splitIntoUnsortedBuckets(List<Integer> initialList){ private List<List<Integer>> splitIntoUnsortedBuckets(List<Integer> initialList){
final int[] codes = createHashes(initialList); final int max = findMax(initialList);
final int numberOfBuckets = (int) Math.sqrt(initialList.size());
List<List<Integer>> buckets = new ArrayList<>(codes[1]); List<List<Integer>> buckets = new ArrayList<>();
for(int i = 0; i < codes[1]; i++) buckets.add(new ArrayList<>()); for(int i = 0; i < numberOfBuckets; i++) buckets.add(new ArrayList<>());
//distribute the data //distribute the data
for (int i : initialList) { for (int i : initialList) {
buckets.get(hash(i, codes)).add(i); buckets.get(hash(i, max, numberOfBuckets)).add(i);
} }
return buckets; return buckets;
} }
private int[] createHashes(List<Integer> input){ private int findMax(List<Integer> input){
int m = input.get(0); int m = Integer.MIN_VALUE;
for (int i = 1; i < input.size(); i++) { for (int i : input){
if (m < input.get(i)) { m = Math.max(i, m);
m = input.get(i);
} }
} return m;
return new int[]{m, (int) Math.sqrt(input.size())};
} }
private static int hash(int i, int[] code) { private static int hash(int i, int max, int numberOfBuckets) {
return (int) ((double) i / code[0] * (code[1] - 1)); return (int) ((double) i / max * (numberOfBuckets - 1));
} }
} }