Node* insert_bucket(Node* head, int value){ int pos = -1; Node* newNode = new Node(value);
if (!head) { return newNode; } if (head->val>value) { // new head newNode->next = head; return newNode; }
Node* pre = head, *cur = head->next; while (!cur && cur->val < value) { pre = cur; cur = cur->next; } newNode->next = cur; pre->next = newNode; return head; }
vector<int> get_bucket(Node* head){ vector<int> result; if (!head) { return result; } while (head) { result.push_back(head->val); head = head->next; } return result; }
vector<int> bucket_sort(vector<int>& array){ int size = array.size(); int min = INT_MAX, max = INT_MIN; for (int i = 0; i < size; i++) { if (array[i] < min) { min = array[i]; } if (array[i] > max) { max = array[i]; } }
int bucket_size = (max - min) / BUCKET_NUM - 1; Node* buckets[BUCKET_NUM]; for (int i = 0; i < BUCKET_NUM; i++) { buckets[i] = NULL; } for (int i = 0; i < size; i++) { int key = array[i] / bucket_size; // bucket number buckets[key] = insert_bucket(buckets[key], array[i]); }
vector<int> result; for (int i = 0; i < BUCKET_NUM; i++) { vector<int> temp = get_bucket(buckets[i]); result.insert(result.end(), temp.begin(), temp.end()); } return result; }
intmain(){ int arr[] = {44, 726, 23, 8, 19, 111}; vector<int> nums(arr, arr + 6); vector<int> result = bucket_sort(nums); for (int i = 0; i < result.size(); i++) { cout << result[i] << " "; } cout << endl; return0; }