summaryrefslogtreecommitdiff
path: root/hist-sort.c
blob: 409dcb138d17231b5e05f6613a677d0651733609 (plain)
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define RANGE 10000
#define COUNT 10000

int is_sorted(unsigned int *data, size_t length)
{
	size_t i = 0;

	for (i = 0; i < length-1; i++)
		if (data[i] > data[i+1])
			return 0;

	return 1;
}

void fill_random(unsigned int *data, size_t length, unsigned int max)
{
	size_t i = 0;

	for (i = 0; i < length; i++)
		data[i] = rand()%max+1;
}

void sort(unsigned int *data, size_t length, unsigned int max)
{
	size_t *hist = calloc(max+1, sizeof(size_t));
	size_t i = 0;
	size_t j = 0;

	for (i = 0; i < length; i++) {
		hist[data[i]]++;
	}

	j = 0;
	for (i = 0; i < max+1; i++) {
		for (; hist[i]; hist[i]--, j++)
			data[j] = i;
	}
}

void dump_data(unsigned int *data, size_t length)
{
	size_t i = 0;

	for (i = 0; i < length; i++)
		printf("%d, ", data[i]);

	fputc('\n', stdout);
}

int main(int argc, char **argv)
{
	unsigned int *data = calloc(COUNT, sizeof(unsigned int));

	if (!data) {
		perror("calloc");
		return 1;
	}

	srand(time(NULL));

	fill_random(data, COUNT, RANGE);

	//dump_data(data, COUNT);
	sort(data, COUNT, RANGE);
	//dump_data(data, COUNT);

	if (!is_sorted(data, COUNT)) {
		fprintf(stderr, "Failed: out of order\n");
	} else {
		printf("Success.\n");
	}
}