Given an array array[], its starting position l and its ending position r. Sort the
array using Bucket Sort algorithm.
8
Input: N = 10
array[] = {10 9 7 8 6 2 4 3 5 1}
Output: 1 2 3 4 5 6 7 8 9 10
#include<iostream>
//Function to obtain maximum item in an array
int max(int arr[], int size){
int m = arr[0];
for(int i=0; i<size; i++){
if(arr[i]>m){
m = arr[i];
}
}
return m;
}
void bucket_sort(int arr[], int n){
int m = max(arr, n);
int bucket[m];
for(int i=0; i<=m; i++)
bucket[i] = 0;
for(int i=0; i<n; i++)
bucket[arr[i]]++;
for(int i=0, j=0; i<=m; i++){
while(bucket[i]>0){
arr[j++] = i;
bucket[i]--;
}
}
}
void display(int arr[], int size){
int i;
for(i=0; i<size; i++){
printf("%d ", arr[i]);
}
}
int main(){
int array[10] = {10, 9, 7, 8, 6, 2, 4, 3, 5, 1};
display(array, 10);
bucket_sort(array,10);
printf("\nAfter bucket sort the array becomes: ");
display(array, 10);
}
Comments
Leave a comment