Bead sort

i need some one to explain this code. how does this unsigned character pointer working code line "bead(i,j)=0". how does it working

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
  #include "stdafx.h"


#include <stdio.h>
#include <stdlib.h>
void bead_sort(int *a, int len)
{
	int i, j, max, sum;
	unsigned char *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 = (unsigned char *)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);
}
int main()
{
	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]);
	system("pause");
	return 0;
}
At line 13, calloc allocates space for max*len bytes. It returns a void * to the space. Line 13 casts the void* to an unsigned char * to assign it to beads.

Line 22 has BEAD(i, j) = 0; This gets converted according to the macro at line 10 into beads[i * max + j] = 0; By the way, the macro is poorly defined. Consider what would happen if you said BEAD(i+1,j) = 3; This would expand to beads[i+1*max+j] = 3; and because multiplication has higher precedence than addition, the index is i+max+j. Macros should always put parenthesis around their arguments in the definition:
#define BEAD(i, j) beads[(i)*max + (j)]
Better still, make it an inline function:
1
2
inline unsigned char BEAD(int i, int j) {return beads[i * max + j]; }
Topic archived. No new replies allowed.