package java_programs;
import java.util.*;

/**
 *
 * @author derricklin
 */
public class BUCKETSORT {
    public static ArrayList<Integer> bucketsort(ArrayList<Integer> arr, int k) {
        int errorReturnCode = -1;  // Assuming -1 is used to indicate an error in bucket index.
        if (k <= 0) return new ArrayList<Integer>(Collections.nCopies(1, errorReturnCode));  // Return error code list if k is zero or negative.

        ArrayList<Integer> counts = new ArrayList<Integer>(Collections.nCopies(k, 0));
        for (Integer x : arr) {
            if (x < 0 || x >= k) {
                return new ArrayList<Integer>(Collections.nCopies(1, errorReturnCode));
            }
            counts.set(x, counts.get(x) + 1);
        }

        ArrayList<Integer> sorted_arr = new ArrayList<Integer>(arr.size());
        int i = 0;
        for (Integer count : counts) {
            sorted_arr.addAll(Collections.nCopies(count, i));
            i++;
        }

        return sorted_arr;
    }
}