File size: 858 Bytes
9438a57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.*;

/**
 * Bucket Sort
 * 
 * 
 * Input:
 *     arr: A list of small ints
 *     k: Upper bound of the size of the ints in arr (not inclusive)
 * 
 * Precondition:
 *     all(isinstance(x, int) and 0 <= x < k for x in arr)
 * 
 * Output:
 *     The elements of arr in sorted order
 *
 * @author derricklin
 */
public class BUCKETSORT {
    public static ArrayList<Integer> bucketsort(ArrayList<Integer> arr, int k) {
        ArrayList<Integer> counts = new ArrayList<Integer>(Collections.nCopies(k,0));
        for (Integer x : arr) {
            counts.set(x,counts.get(x)+1);
        }

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

        return sorted_arr;
    }
}