Quantcast
Channel: The Crazy Programmer
Viewing all articles
Browse latest Browse all 761

Bucket Sort in C and C++

$
0
0

Here you will get program for bucket sort in C and C++.

In bucket sort algorithm the array elements are distributed into a number of buckets. Then each bucket sorted individually either using any other sorting algorithm or by recursively applying bucket sort.

Take example shown in below image.

Bucket Sort

Elements are distributed among buckets

Bucket Sort

Then, elements are sorted within each bucket

Below is the program to implement this algorithm. In this program it is assumed that the array elements are between 0 to 10.

Program for Bucket Sort in C

#include<stdio.h>

#define SIZE 10

void bucketSort(int a[], int n) {
	int i, j, k, buckets[SIZE];
	
	for(i = 0; i < SIZE; ++i)
		buckets[i] = 0;
	
	for(i = 0; i < n; ++i)
		++buckets[a[i]];
		
	for(i = 0, j = 0; j < SIZE; ++j)
		for(k = buckets[j]; k > 0; --k)
			a[i++] = j;
}

int main() {
	int i, a[] = {3, 6, 5, 1, 8, 4, 3, 1}, n = 8;
	
	printf("Before sorting:\n");
	for(i = 0; i < n; ++i)
		printf("%d ", a[i]);
	
	bucketSort(a, 8);
	
	printf("\n\nAfter sorting:\n");
	for(i = 0; i < n; ++i)
		printf("%d ", a[i]);
	
	return 0;
}

Program for Bucket Sort in C++

#include<iostream>

#define SIZE 10

using namespace std;

void bucketSort(int a[], int n) {
	int i, j, k, buckets[SIZE];
	
	for(i = 0; i < SIZE; ++i)
		buckets[i] = 0;
	
	for(i = 0; i < n; ++i)
		++buckets[a[i]];
		
	for(i = 0, j = 0; j < SIZE; ++j)
		for(k = buckets[j]; k > 0; --k)
			a[i++] = j;
}

int main() {
	int i, a[] = {3, 6, 5, 1, 8, 4, 3, 1}, n = 8;
	
	cout << "Before sorting:\n";
	for(i = 0; i < n; ++i)
		cout << a[i] << " ";
	
	bucketSort(a, 8);
	
	cout<< "\n\nAfter sorting:\n";
	for(i = 0; i < n; ++i)
		cout<< a[i] << " ";
	
	return 0;
}

Output

Before sorting:
3 6 5 1 8 4 3 1

After sorting:
1 1 3 3 4 5 6 8

The post Bucket Sort in C and C++ appeared first on The Crazy Programmer.


Viewing all articles
Browse latest Browse all 761

Trending Articles