summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDavid Phillips <david@sighup.nz>2017-04-06 15:26:27 +1200
committerDavid Phillips <david@sighup.nz>2017-04-06 15:26:27 +1200
commit7208221ed45d1b4fddf876ac6f072f0c36cab270 (patch)
tree9f559b6efabdc931b80c8a953ec4e3a4539006db
parente48df354af82d2b691c33d66821a0a520d0c2e44 (diff)
downloadinteresting-sorts-7208221ed45d1b4fddf876ac6f072f0c36cab270.tar.xz
Improve documentation, add comamnd line arguments
-rw-r--r--hist-sort.c48
1 files changed, 27 insertions, 21 deletions
diff --git a/hist-sort.c b/hist-sort.c
index cf7a0dd..423f026 100644
--- a/hist-sort.c
+++ b/hist-sort.c
@@ -19,9 +19,6 @@
#include <stdlib.h>
#include <time.h>
-#define RANGE 10000
-#define COUNT 10000000
-
int
is_sorted(unsigned int *data, size_t length) {
size_t i = 0;
@@ -52,32 +49,43 @@ sort(unsigned int *data, size_t length, unsigned int max) {
return;
}
- for (i = 0; i < length; i++) {
+ /* build the histogram */
+ for (i = 0; i < length; i++)
hist[data[i]]++;
- }
+ /* expand histogram to form sorted set */
j = 0;
- for (i = 0; i < max+1; i++) {
+ 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);
+show_usage(const char *argv0) {
+ fprintf(stderr, "usage: %s <item_count> <max_value>\n", argv0);
}
int
main(int argc, char **argv) {
clock_t start, end;
- unsigned int *data = calloc(COUNT, sizeof(unsigned int));
+ unsigned int *data = NULL;
+ int range = 0;
+ int count = 0;
+
+ if (argc != 3) {
+ show_usage(argv[0]);
+ return 1;
+ }
+
+ count = atoi(argv[1]);
+ range = atoi(argv[2]);
+
+ if (count <= 0 || range <= 0) {
+ show_usage(argv[0]);
+ return 1;
+ }
+ data = calloc(count, sizeof(unsigned int));
if (!data) {
perror("calloc");
return 1;
@@ -85,18 +93,16 @@ main(int argc, char **argv) {
srand(time(NULL));
- fill_random(data, COUNT, RANGE);
+ fill_random(data, count, range);
- //dump_data(data, COUNT);
start = clock();
- sort(data, COUNT, RANGE);
+ sort(data, count, range);
end = clock();
- //dump_data(data, COUNT);
- printf("Time elapsed to sort: %.4f\n",
+ printf("Time taken to sort: %.4f\n",
((double)(end-start))/CLOCKS_PER_SEC);
- if (!is_sorted(data, COUNT)) {
+ if (!is_sorted(data, count)) {
fprintf(stderr, "Failed: out of order\n");
} else {
printf("Success.\n");