bucket sort Implementation without using vector,pointer and counting sort

1.2k Views Asked by At

We want to use Bucket sort to sort numbers between 1 to 2001. the count of numbers can be 10E6.

I know the bucket sort algorithm. But the issue is that in this question, we are not permitted to use variable-length array, vector and pointer. (The only pointer related thing allowed is "pass by reference" of the array) The only solution I found is using using counting sort for each bucket, like the code below, so the code is more like counting sort than the bucket sort: (C language)

#include <stdio.h>
int buckets[201][10]={}; int numbers[1000001]={};

void bucket_sort (int a[],int n) {
    for (int i =0;i<=n-1;i++)
    {
        int index = a[i]/10, index2 = a[i]%10;
        buckets[index][index2]++;
    }
    int counter =0;
    for (int i =0;i<=200;i++)
    {
        for (int j =0; j<=9;j++)
        {
            while (buckets[i][j])
            {
                a[counter] = i*10+j; 
                counter++;
                buckets[i][j]--;
            }
        }
    } }

int main() {
    int n;
    scanf("%d",&n);
    if (n==0)
    {
        return 0;
    }
    for (int i =0;i<=n-1;i++)
    {
        scanf("%d",&numbers[i]);
        numbers[i]; 
    }
    bucket_sort(numbers,n);
    for (int i =0;i<=n-1 ;i++)
    {
        printf("%d\n", numbers[i]);
    }
    return 0; }

I want to know can bucket sort be implemented without variable-length array, vector and pointer and also without counting sort. Probably using Insertion or Bubble sort. Note that it must be a reasonable bucket-sort algorithm. So defining very big buckets like int bucket [201][1000000]; is also an unacceptable approach.

1

There are 1 best solutions below

2
dbush On

Given that you can't use variable length arrays or pointers, one of which is required for a bucket sort, your best bet is to go with a counting sort. You only have 2000 possible values, so create an array of size 2000 and for each value you find increments the corresponding array element.

void counting_sort(int a[], int n)
{
    int count[2002] = { 0 };
    int i, j; 

    for (i=0; i<n; i++) {
        count[a[i]]++;
    }

    for (i=0, j=0; i<n; i++) {
        while (!count[j]) {
            j++;
        }
        a[i] = j;
        count[j]--;
    }
}