Tuesday, August 10, 2021

Radix Sort in C

 A simple radix sort program that I wrote in C programming  thank you to my friend Tom helping me out fixing some bugs in this code.

 I am currently accepting programming work, IT projects, school and application development, programming projects, thesis and capstone projects, IT consulting work, computer tutorials, and web development work kindly contact me at the following email address for further details.  If you want to advertise on my website, kindly contact me also at my email address also. Thank you.

My email address is jakerpomperada@gmail.com and jakerpomperada@yahoo.com

My mobile number here in the Philippines is 09173084360.





Program Listing

radix.c

/* radix.c

   Jake Rodriguez Pomperada,MAED-IT, MIT

   www.jakerpomperada.com   www.jakerpomperada.blogspot.com

   jakerpomperada@gmail.com

   Bacolod City, Negros Occidental */


#define  _CRT_SECURE_NO_WARNINGS // only needed for Visual Studio

#include <stdio.h>

#include <stdlib.h>


static void radixsort(int Array[], int n);

static void countingsort(int Array[], int n, int place);

static void PrintArray(int Array[], int n);



void radixsort(int Array[], int n)

{

int i = 0, place = 0;

int max = Array[0];


for (i = 1; i < n; i++) {

if (max < Array[i])

max = Array[i];

}



for (place = 1; max / place > 0; place *= 10)

countingsort(Array, n, place);

}


static void countingsort(int Array[], int n, int place) {

int i;

int* output = malloc(sizeof(int) * n);

if (output == NULL)

{

fprintf(stderr, "%s", "Out of memory");

return;

}


int freq[10] = { 0 };



for (i = 0; i < n; i++)

freq[(Array[i] / place) % 10]++;



for (i = 1; i < 10; i++)

freq[i] += freq[i - 1];



for (i = n - 1; i >= 0; i--) {

output[freq[(Array[i] / place) % 10] - 1] = Array[i];

freq[(Array[i] / place) % 10]--;

}


for (i = 0; i < n; i++)

Array[i] = output[i];


free(output);

}



static void PrintArray(int Array[], int n) {

    printf("\t");

for (int i = 0; i < n; i++)


printf("%i ", Array[i]);

printf("\n");

}



int main() {


int a = 0, num = 0;

system("cls");

printf("\n\n");

printf("\tRadix Sort Program in C");

printf("\n\n");

printf("\tHow many items? : ");

scanf("%d", &num);

printf("\n\n");

int* b = malloc(sizeof(int) * num);

if (b == NULL)

{

fprintf(stderr, "%s", "Out of memory");

return;

}

for (a = 0; a < num; a++) {

printf("\tEnter item no. %d: ", a + 1);

scanf("%d", &b[a]);

}


printf("\n\n");

printf("\tOriginal Array\n\n");

PrintArray(b, num);


radixsort(b, num);

    printf("\n\n");

printf("\tSorted Array\n\n");

PrintArray(b, num);

free(b);

return 0;

}


No comments:

Post a Comment