Radix Sort in C Programming

In this source code example, we will write a code to implement the Radix Sort algorithm in the C programming language.

Radix Sort in C Programming

Radix Sort in C Programming

In this C program, we will take input from the User or console. 

Let's write a C program to sort N numbers in ascending order using the Radix Sort algorithm:

#include<stdio.h>

void Radixsort(int[], int);

void main() {
	int x[20], i, n;
	printf("\n Enter the no of element to be sorted:");
	scanf("%d", &n);
	printf("\n Enter %d elements:", n);
	for (i = 0; i < n; i++)
		scanf("%d", &x[i]);
	Radixsort(x, n);
	printf("\n The sorted array is:\n");
	for (i = 0; i < n; i++)
		printf("%4d", x[i]);
}

void Radixsort(int a[], int n) {
	int bucket[10][10], buck[10];
	int i, j, k, l, num, div, large, pass;
	div = 1;
	num = 0;
	large = a[0];
	for (i = 0; i < n; i++) {
		if (a[i] > large)
			large = a[i];
	}
	while (large > 0) {
		num = num + 1;
		large = large / 10;
	}
	for (pass = 0; pass < num; pass++) {
		for (k = 0; k < 10; k++)
			buck[k] = 0;
		for (i = 0; i < n; i++) {
			l = (a[i] / div) % 10;
			bucket[l][buck[l]++] = a[i];
		}
		i = 0;
		for (k = 0; k < 10; k++) {
			for (j = 0; j < buck[k]; j++)
				a[i++] = bucket[k][j];
		}
		div = div * 10;
	}
}

Output:


 Enter the no of element to be sorted:
5

 Enter 5 elements:
10
50
30
20
40

 The sorted array is:
  10  20  30  40  50

Related Algorithms in C Programming


Comments