Answer to Question #276746 in C for MRM

Question #276746

Given an array array[], its starting position l and its ending position r. Sort the array using Bucket Sort algorithm.

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 


1
Expert's answer
2021-12-08T03:06:43-0500
#include <stdio.h>  




int  getMaximumElement(int array[], int n)
{  
	int max = array[0];  
	int i;
	for (i = 1; i < n; i++){
		if (array[i] > max){
			max = array[i];  
		}
	} 
	return max;  
}  
void bucketSort(int array[], int n) // function to implement bucket sort  
{  
	int max = getMaximumElement(array, n); //max is the maximum element of array  
	int bucket[100], i,j;  
	for (i = 0; i <= max; i++)  
	{  
		bucket[i] = 0;  
	}  
	for (i = 0; i < n; i++)  
	{  
		bucket[array[i]]++;  
	}  
	for (i = 0, j = 0; i <= max; i++)  
	{  
		while (bucket[i] > 0)  
		{  
			array[j++] = i;  
			bucket[i]--;  
		}  
	}  
}  
void printArrayElements(int array[], int n) 
{  
	for (int i = 0; i < n; ++i) {
		printf("%d  ", array[i]);  
	}
	
}  
int main()  
{  
	int const N=10;
	int array[] = {10,9,7,8,6,2,4,3,5,1};
	printf("Before sorting array elements are:\n");  
	printArrayElements(array, N);  
	bucketSort(array, N);  
	printf("\nAfter sorting array elements are:\n");  
	printArrayElements(array, N);


	getchar();
	getchar();


	return 0;
}  

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS