MCPcopy Create free account
hub / github.com/Lakhankumawat/LearnCPP / BucketSort

Function BucketSort

S-SortingAlgorithms/BucketSort.cpp:26–97  ·  view source on GitHub ↗

Sorting function

Source from the content-addressed store, hash-verified

24
25// Sorting function
26void BucketSort(double arr[])
27{
28 int i, j;
29 struct Node **buckets;
30
31 // Create buckets and allocate memory size
32 buckets = (struct Node **)malloc(sizeof(struct Node *) * NBUCKET);
33
34 // Initialize empty buckets
35 for (i = 0; i < NBUCKET; ++i)
36 {
37 buckets[i] = NULL;
38 }
39
40 // Fill the buckets with respective elements
41 for (i = 0; i < NARRAY; ++i)
42 {
43 struct Node *current;
44 int pos = getBucketIndex(arr[i]);
45 current = (struct Node *)malloc(sizeof(struct Node));
46 current->data = arr[i];
47 current->next = buckets[pos];
48 buckets[pos] = current;
49 }
50
51 // Print the buckets along with their elements
52 for (i = 0; i < NBUCKET; i++)
53 {
54 cout << "Bucket[" << i << "] : ";
55 printBuckets(buckets[i]);
56 cout << endl;
57 }
58
59 // Sort the elements of each bucket
60 for (i = 0; i < NBUCKET; ++i)
61 {
62 buckets[i] = InsertionSort(buckets[i]);
63 }
64
65 cout << "-------------" << endl;
66 cout << "Bucktets after sorted" << endl;
67 for (i = 0; i < NBUCKET; i++)
68 {
69 cout << "Bucket[" << i << "] : ";
70 printBuckets(buckets[i]);
71 cout << endl;
72 }
73
74 // Put sorted elements on arr
75 for (j = 0, i = 0; i < NBUCKET; ++i)
76 {
77 struct Node *node;
78 node = buckets[i];
79 while (node) {
80 arr[j++] = node->data;
81 node = node->next;
82 }
83 }

Callers 1

showResFunction · 0.85

Calls 3

getBucketIndexFunction · 0.85
printBucketsFunction · 0.85
InsertionSortFunction · 0.85

Tested by

no test coverage detected