This is what i have so far but its not giving me the output i want. I need the array that the user will fill be sorted by using bitwise operations in the radix sort function. The instructions for this states that i should use the bitwise operations to extract the bits and then use the value of the bits as the bucket indexes.
void radix_sort(unsigned int *array, int num, int bits);
int main()
{
int bits = 32;
int num = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
unsigned int array[100];
if(num > 100)
{
printf("Number of elements cannot be greater than 100.");
}
else
{
for(int i = 0; i < num; i++)
{
unsigned int elem;
printf("Enter a number: ");
scanf("%u", &array[i]);
//array[i] = elem;
//printf("%d\n", array[i]);
}
}
radix_sort(array, num, bits);
for(int i = 0; i < num; i++)
{
printf("%u\n", array[i]);
}
return 0;
}
void radix_sort(unsigned int *array, int num, int bits)
{
unsigned int bucket_0[num];
unsigned int bucket_1[num];
for(int d = 0; d < bits; d++)
{
int count0 = 0;
int count1 = 0;
for(int i = 0; i < num; i++)
{
if( ( array[d] & (1 >> i) ) != 0)
{
bucket_1[i] = array[d];
count1++;
}
else
{
bucket_0[i]= array[d];
count0++;
}
}
int i = 0;
for(int j = 0; j < count0; ++i, ++j)
{
array[i] = bucket_0[j];
//printf("%d\n",bucket_0[j]);
}
for(int j = 0; j < count1; ++i, ++j)
{
array[i] = bucket_1[j];
}
}
}
Couple of obvious typo errors:
when putting elements into the buckets, you should use
bucket_1[count1] = array[i]andbucket_0[count0] = array[i]rather than what you haveyou've swapped
ianddin a number of places1 >> iwill be 0 when i > 0 -- you want1 << dinstead.