Bucket Sort in C
Here you will know Bucket Sort algorithm and get the program code of Bucket Sort in C programming.
What is Bucket sort
Bucket Sort or bin Sort is a sorting method that divides data into “buckets,” each holding similar values. These buckets are then sorted, and their contents are combined to produce a sorted list.
Bucket Sort is often used as a step in other sorting algorithms, such as Quick Sort.
Elements are distributed among bins
Then, elements are sorted within each bin
Bucket Sort Algorithm
Bucket sort is a sorting algorithm that sorts items into buckets based on their values. It is a comparison sort algorithm that is both efficient and stable.
1. Create an array of buckets (initially empty)
2. Iterate through the input array and place each element in the correct bucket.
3. Sort each non-empty bucket using a different sorting algorithm.
4. Iterate through the buckets and collect the elements in sorted order.
Bucket sort is an efficient algorithm for sorting elements with a range that is small compared to the number of elements. It can be used to sort elements quickly in linear time if the range of values is known in advance.
Program for Bucket Sort in C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | #include <stdio.h> #include <stdlib.h> #define MAX 50 void bucketSort(int arr[], int n) { int i, j; int ct[MAX]; for (i=0; i<MAX; i++) ct[i] = 0; for (i=0; i<n; i++) (ct[arr[i]])++; for (i=0,j=0; i<MAX; i++) for(; ct[i]>0; (ct[i])--) arr[j++] = i; } int main() { int arr[50],num,i; printf("\n***** Counting Sort in C *****\n\n"); printf("\n Enter Number of elements : "); scanf("%d",&num); printf("\n Enter value of elements : "); for (i=0; i<num; i++) scanf("%d",&arr[i]); bucketSort(arr, num); printf("\n sorted array:"); for (i=0; i<num; i++) printf("%d ",arr[i]); return 0; } |
Output
Read Also