Search code examples
c++algorithmsortingbucket

Writing bucket sort in c++


A book I have says this:

a) Place each value of the one-dimensional array into a row of the bucket array based on the value's ones digit. For example, 97 is placed in row 7, 3 is placed in row 3, and 100 is placed in row 0. This is called a "distribution pass."

b) Loop through the bucket array row by row, and copy the values back to the original array. This is called a "gathering pass." The new order of the preceding values in the one-dimensional array is 100, 3, and 97.

c) Repeat this process for each subsequent digit position.

I am having a lot of trouble trying to understand and implement this. So far I have:

void b_sort(int sarray[], int array_size) {
    const int max = array_size;
    for(int i = 0; i < max; ++i)
        int array[i] = sarray[i];

    int bucket[10][max - 1];
}

I'm thinking that in order to sort them by ones, tens, hundreds, etc, I can use this:

for(int i = 0; i < max; ++i)
    insert = (array[i] / x) % 10;
    bucket[insert];

where x = 1, 10, 100, 1000, etc. I am totally lost on how to write this now.


Solution

  • Here's a bucket sort based on the info in the OP question.

    void b_sort(int sarray[], int array_size) {
        const int max = array_size;
        // use bucket[x][max] to hold the current count
        int bucket[10][max+1];
        // init bucket counters
        for(var x=0;x<10;x++) bucket[x][max] = 0;
        // main loop for each digit position
        for(int digit = 1; digit <= 1000000000; digit *= 10) {
            // array to bucket
            for(int i = 0; i < max; i++) {
                // get the digit 0-9
                int dig = (sarray[i] / digit) % 10;
                // add to bucket and increment count
                bucket[dig][bucket[dig][max]++] = sarray[i];
            }
            // bucket to array
            int idx = 0;
            for(var x = 0; x < 10; x++) {
                for(var y = 0; y < bucket[x][max]; y++) {
                    sarray[idx++] = bucket[x][y];
                }
                // reset the internal bucket counters
                bucket[x][max] = 0;
            }
        }
    }
    

    Notes Using a 2d array for the bucket wastes a lot of space... an array of queues/lists usually makes more sense.

    I don't normally program in C++ and the above code was written inside the web browser, so syntax errors may exist.