Bucket Sort
Bucket sort is also known as bin sort. It works by distributing the element into the array also called buckets. Buckets are sorted individually by using different sorting algorithm.
Complexity of Bucket Sort
Algorithm | Complexity |
---|---|
Space | O(1) |
Worst Case | O(n2) |
Best Case | Ω(n+k) |
Average Case | θ(n+k) |
Algorithm
- Step 1 START
- Step 2 Set up an array of initially empty "buckets".
- Step 3 Scatter: Go over the original array, putting each object in its bucket.
- Step 4 Sort each non-empty bucket.
- Step 5 Gather: Visit the buckets in order and put all elements back into the original array.
- Step 6 STOP
Program
- #include <stdio.h>
- void Bucket_Sort(int array[], int n)
- {
- int i, j;
- int count[n];
- for (i = 0; i < n; i++)
- count[i] = 0;
- for (i = 0; i < n; i++)
- (count[array[i]])++;
- for (i = 0, j = 0; i < n; i++)
- for(; count[i] > 0; (count[i])--)
- array[j++] = i;
- }
- /* End of Bucket_Sort() */
- /* The main() begins */
- int main()
- {
- int array[100], i, num;
- printf("Enter the size of array : ");
- scanf("%d", &num);
- printf("Enter the %d elements to be sorted:\n",num);
- for (i = 0; i < num; i++)
- scanf("%d", &array[i]);
- printf("\nThe array of elements before sorting : \n");
- for (i = 0; i < num; i++)
- printf("%d ", array[i]);
- printf("\nThe array of elements after sorting : \n");
- Bucket_Sort(array, num);
- for (i = 0; i < num; i++)
- printf("%d ", array[i]);
- printf("\n");
- return 0;
- }