Bucket sort help Sorts a few of the numbers however it doesn
Bucket sort help! Sorts a few of the numbers, however, it doesn\'t fully sort all integers. Some numbers are being repeated. Suspect that problem is in the last loop of function.
void bucketSort (int arr[], int count)
{
int minValue = arr[0];
int maxValue = arr[0];
for (int i = 1; i < count; i++)
{
if (arr[i] > maxValue)
{
maxValue = arr[i];
}
if (arr[i] < minValue)
{
minValue = arr[i];
}
}
int range = maxValue - minValue;
//Create empty buckets
int buckets[range];
//Intialize all buckets to 0
for (int i = 0; i < range; i++)
buckets[i] = 0;
//Increment the number of times each element is present in the input
//array. Insert them in the buckets
for (int i = 0; i < count; i++)
buckets[arr[i]]++;
//Sort using insertion sort and concatenate
for (int i = 0, j = 0; j < range; j++)
for (int k = buckets[j]; k > 0; k--)
arr[i++] = j;
}
Solution
Problem lies in the number of buckets you are creating to store number.
If number\'s lie between 1 and 100 then total number of buckets will be 101 thus
int range = maxValue - minValue + 2;
Following is the correct function.
void bucketSort (int arr[], int count)
{
int minValue = arr[0];
int maxValue = arr[0];
for (int i = 1; i < count; i++)
{
if (arr[i] > maxValue)
{
maxValue = arr[i];
}
if (arr[i] < minValue)
{
minValue = arr[i];
}
}
int range = maxValue - minValue + 2;
//Create empty buckets
int buckets[range];
//Intialize all buckets to 0
for (int i = 0; i < range; i++)
buckets[i] = 0;
//Increment the number of times each element is present in the input
//array. Insert them in the buckets
for (int i = 0; i < count; i++)
buckets[arr[i]]++;
//Sort using insertion sort and concatenate
for (int i = 0, j = 0; j < range; j++)
for (int k = buckets[j]; k > 0; k--)
arr[i++] = j;
}

