#include<stdio.h>#include<stdlib.h>voidbead_sort(int*a,int len){
int i, j, max, sum;unsignedchar*beads;# define BEAD(i, j) beads[i * max + j]for(i =1, max = a[0]; i < len; i++)if(a[i]> max) max = a[i];
beads =calloc(1, max * len);/* mark the beads */for(i =0; i < len; i++)for(j =0; j < a[i]; j++)BEAD(i, j)=1;for(j =0; j < max; j++){
/* count how many beads are on each post */for(sum = i =0; i < len; i++){
sum +=BEAD(i, j);BEAD(i, j)=0;}/* mark bottom sum beads */for(i = len - sum; i < len; i++)BEAD(i, j)=1;}for(i =0; i < len; i++){
for(j =0; j < max &&BEAD(i, j); j++);
a[i]= j;}free(beads);}intmain(){
int i, x[]={
5,3,1,7,4,1,1,20};int len =sizeof(x)/sizeof(x[0]);bead_sort(x, len);for(i =0; i < len; i++)printf("%d\n", x[i]);return0;}
C++
//this algorithm only works with positive, whole numbers.//O(2n) time complexity where n is the summation of the whole list to be sorted. //O(3n) space complexity.#include<iostream>#include<vector>using std::cout;using std::vector;voiddistribute(int dist, vector<int>&List){
//*beads* go down into different buckets using gravity (addition).if(dist > List.size())
List.resize(dist);//resize if too big for current vectorfor(int i=0; i < dist; i++)
List[i]++;}
vector<int>beadSort(int*myints,int n){
vector<int> list, list2, fifth (myints, myints + n);
cout <<"#1 Beads falling down: ";for(int i=0; i < fifth.size(); i++)
distribute (fifth[i], list);
cout <<'\n';
cout <<"\nBeads on their sides: ";for(int i=0; i < list.size(); i++)
cout <<" "<< list[i];
cout <<'\n';//second part
cout <<"#2 Beads right side up: ";for(int i=0; i < list.size(); i++)
distribute (list[i], list2);
cout <<