Question

In: Computer Science

I have implemented Bucket_Sort, it successfully executed but not give desire output(all the element is not...

I have implemented Bucket_Sort, it successfully executed but not give desire output(all the element is not sorted), please help me out with this code

#include<iostream>

using namespace std;

struct Node{

    int data;

    Node *next;

};

int Max(int arr[], int n)

{

    int max=0;

    for (int i = 0; i < n; i++)

    {

        if (arr[i] > max)

        {

            max = arr[i];

        }

    }

    return max;

}

void Bucket_Sort(int arr[], int n)

{

    int max = Max(arr,n);

    Node *bin[max+1] = {NULL};

    Node *newnode;

    Node *temp;

    for (int i = 0; i < n; i++)

    {  

        newnode = new Node();

        newnode->data = arr[i];

        newnode->next = NULL;

        if (bin[arr[i]] == NULL)

        {   

            bin[arr[i]] = temp = newnode;

        }else

        {

            temp->next = newnode;

            temp = newnode;

            

        }

    }

    int j=0,k=0;

    while (j < max+1)

    {   Node *temp;

        if (bin[j] != NULL)

        {   temp = bin[j];

            while (temp != NULL)

            {   arr[k++] = temp->data;

                temp = temp->next;

            }

            

        }

        j++;

    }

    for (int i = 0; i < n; i++)

    {

        cout<<arr[i]<<" ";

    }

    

}

int main()

{

   int arr[] = {6,8,3,10,15,6,9,12,6,3};

   int n=10;

   Bucket_Sort(arr,n);

   return 0;

}

Solutions

Expert Solution

Bucket sort is a comparison sorting algorithm. It scans elements and put these into different buckets. Each bucket is sorted individually using a sorting algorithm of your choice. Here i used insertion sort for sorting the elements in the bucket.

i used static type of programming, you can modify the program by entering user defined values for sorting using cin function. The following is the source code that will helps you to sort elements using buckets. Here the bucket size is 5 and the bucket range is 10 and number of elements taken is 10. u can change them as required.

Source Code for Bucket Sorting:

#include <iostream>
#include <iomanip>
using namespace std;

#define NARRAY 10 /* array size */
#define NBUCKET 5 /* bucket size */
#define INTERVAL 10 /* bucket range */

struct Node
{
   int data;
   struct Node *next;
};

void BucketSort(int arr[]);
struct Node *InsertionSort(struct Node *list);
void print(int arr[]);
void printBuckets(struct Node *list);
int getBucketIndex(int value);

void BucketSort(int arr[])
{  
   int i,j;
   struct Node **buckets;

   /* allocate memory for array of pointers to the buckets */
   buckets = (struct Node **)malloc(sizeof(struct Node*) * NBUCKET);

   /* initialize pointers to the buckets */
   for(i = 0; i < NBUCKET;++i) {
       buckets[i] = NULL;
   }

   /* put items into the buckets */
   for(i = 0; i < NARRAY; ++i) {  
       struct Node *current;
       int pos = getBucketIndex(arr[i]);
       current = (struct Node *) malloc(sizeof(struct Node));
       current->data = arr[i];
       current->next = buckets[pos];
       buckets[pos] = current;
   }

   /* check what's in each bucket */
   for(i = 0; i < NBUCKET; i++) {
       cout << "Bucket[" << i << "] : ";
   printBuckets(buckets[i]);
       cout << endl;
   }

   /* sorting bucket using Insertion Sort */
   for(i = 0; i < NBUCKET; ++i) {
       buckets[i] = InsertionSort(buckets[i]);
   }

   /* check what's in each bucket */
   cout << "-------------" << endl;
   cout << "Bucktets after sorted" << endl;
   for(i = 0; i < NBUCKET; i++) {
       cout << "Bucket[" << i << "] : ";
   printBuckets(buckets[i]);
       cout << endl;
   }

   /* put items back to original array */
   for(j =0, i = 0; i < NBUCKET; ++i) {  
       struct Node *node;
       node = buckets[i];
       while(node) {
           arr[j++] = node->data;
           node = node->next;
       }
   }
  
   /* free memory */
   for(i = 0; i < NBUCKET;++i) {  
       struct Node *node;
       node = buckets[i];
       while(node) {
           struct Node *tmp;
           tmp = node;
           node = node->next;
           free(tmp);
       }
   }
   free(buckets);
   return;
}

/* Insertion Sort */
struct Node *InsertionSort(struct Node *list)
{  
   struct Node *k,*nodeList;
   /* need at least two items to sort */
   if(list == 0 || list->next == 0) {
       return list;
   }
  
   nodeList = list;
   k = list->next;
   nodeList->next = 0; /* 1st node is new list */
   while(k != 0) {  
       struct Node *ptr;
       /* check if insert before first */
       if(nodeList->data > k->data) {
           struct Node *tmp;
           tmp = k;
           k = k->next;
           tmp->next = nodeList;
           nodeList = tmp;
           continue;
       }

       for(ptr = nodeList; ptr->next != 0; ptr = ptr->next) {
           if(ptr->next->data > k->data) break;
       }

       if(ptr->next!=0){
           struct Node *tmp;
           tmp = k;
           k = k->next;
           tmp->next = ptr->next;
           ptr->next = tmp;
           continue;
       }
       else{
           ptr->next = k;
           k = k->next;
           ptr->next->next = 0;
           continue;
       }
   }
   return nodeList;
}

int getBucketIndex(int value)
{
   return value/INTERVAL;
}

void print(int ar[])
{  
   int i;
   for(i = 0; i < NARRAY; ++i) {
       cout << setw(3) << ar[i];
   }
   cout << endl;
}

void printBuckets(struct Node *list)
{
   struct Node *cur = list;
   while(cur) {
       cout << setw(3) << cur->data;
       cur = cur->next;
   }
}

int main(void)
{  
   int array[NARRAY] = {6,8,3,10,15,6,9,12,6,3};

   cout << "Initial array" << endl;
   print(array);
   cout << "-------------" << endl;

   BucketSort(array);
   cout << "-------------" << endl;
   cout << "Sorted array" << endl;
   print(array);
   return 0;
}


Related Solutions

I have the below program and I am having issues putting all the output in one...
I have the below program and I am having issues putting all the output in one line instead of two. how can I transform the program for the user enter format ( HH:MM) Like: Enter time using 24 format ( HH:MM) : " and the user enter format " 14:25 then the program convert. instead of doing two lines make all one line. Currently I have the user enter first the Hour and then the minutes but i'd like to...
Many entrepreneurs have the desire to become successful CEOs, but not all will succeed. The period...
Many entrepreneurs have the desire to become successful CEOs, but not all will succeed. The period of transition during which a startup grows up and becomes a scalable business is arguably the most critical time in the life of an emerging firm. In his 2018 interview, Airbnb founder Bryan Chesky states that "(after growing your startup, you reach a point where) you realize that everything you do doesn’t matter because your company is too big and you need to run...
I have been given a project to do that will have the potential of being implemented....
I have been given a project to do that will have the potential of being implemented. The scope of the project is to come up with a remote monitoring system for the status of a pump-motor arrangement which has a valve in front of it that also had to be monitored. The level of the water in the tank where the pump is pumping has to be monitored by the use of float switches. This all has to be with...
Give the electron configuration for an element with 19 electrons. How many valence electrons does this element have?
Give the electron configuration for an element with 19 electrons. How many valence electrons does this element have?
hi i need a code that will give me this output, For the multiply_list, the user...
hi i need a code that will give me this output, For the multiply_list, the user will be asked to input the length of the list, then to input each element of the list. For the repeat_tuple, the user is only asked to enter the repetition factor, but not the tuple. Your program should take the list created before and convert it to a tuple. output expected: (**user input**) ******Create your List ****** Enter length of your list: 3 ******...
c# code working but output not right, I need to output all numbers like : Prime...
c# code working but output not right, I need to output all numbers like : Prime factors of 4 are: 2 x 2 here is just 2 Prime factors of 7 are: 7 Prime factors of 30 are: 2 x 3 x 5 Prime factors of 40 are: 2 x 2 x 2 x 5 here is just 2,5 Prime factors of 50 are: 2 x 5 x 5 here is just 2,5 1) How I can fix it 2)I...
What knowledge must a manager have to successfully influence organization members of multinational corporations? Give an...
What knowledge must a manager have to successfully influence organization members of multinational corporations? Give an example of a manager (or leader) that has done a good job of influencing a multinational organization.
For the following reaction show all work: 1. Give the oxidation number for each element in...
For the following reaction show all work: 1. Give the oxidation number for each element in the following equation. Fe2O3 (s) + CO (g) = Fe (s) + CO2 (g) a. Write the balanced oxidation half reaction. b. Write the balanced reduction half reaction. c. What is the oxidizing agent? d. What is the reducing agent? e. What is the net ionic equation?
I have to translate C++ code into MIPS. It is expected to have an output of:...
I have to translate C++ code into MIPS. It is expected to have an output of: Value of a: 25 Value of b: 31 Value of c: 18 Value of d: 49 Here is the C++ code: I need to translate this C++ into MIPS code. #include using namespace std; int main(void) { int a = 5; int b = 6; int c = 7; int d; d = -1; if ( a < 10){ a++; }else{ a--; } d...
a. Give an example from your professional experience where you have identified and implemented an improvement...
a. Give an example from your professional experience where you have identified and implemented an improvement in the work processes/activities. b. Explain how you would communicate the savings and productivity/service improvements achievements to the relevant personnel within or outside the organisation
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT