Fakultas Ilmu Komputer UI

Commit cdd8f98d authored by Avatar Azka's avatar Avatar Azka

[WIP] Added bucket sort algorithm

parent 68fa6983
package daa;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
// write your code here
// write your code here
int arr[] = {3, 4, 2, 5, 7, 1, 2, 8, 10, 22, 93, 52};
int size = arr.length;
List<Integer> out = bucketSort(arr, size);
System.out.println("Result: ");
System.out.println(out);
}
private static int hash(int i, int max, int numberOfBuckets) {
return (int) ((double) i / max * (numberOfBuckets - 1));
}
private static int findMax(int input[]) {
int m = Integer.MIN_VALUE;
for (int i : input) {
m = Math.max(i, m);
}
return m;
}
// TODO: Add bucket sort
public static void bucketSort() {
// FIXME: Temp bucketsort alg, from baeldung
// Edit if needed
public static List<Integer> bucketSort(int arr[], int size) {
final int numberOfBuckets = (int) Math.sqrt(arr.length);
List<List<Integer>> buckets = new ArrayList<>(numberOfBuckets);
for(int i = 0; i < numberOfBuckets; i++) {
buckets.add(new ArrayList<>());
}
int max = findMax(arr);
for (int i : arr) {
buckets.get(hash(i, max, numberOfBuckets)).add(i);
}
Comparator<Integer> comparator = Comparator.naturalOrder();
for(List<Integer> bucket : buckets){
bucket.sort(comparator);
}
List<Integer> sortedArray = new LinkedList<>();
for(List<Integer> bucket : buckets) {
sortedArray.addAll(bucket);
}
return sortedArray;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment