diff CbC-examples/quicksort/quicksort_test.cbc @ 22:0eb6cac880f0

add cbc example of quicksort.
author kent <kent@cr.ie.u-ryukyu.ac.jp>
date Tue, 13 Oct 2009 17:15:58 +0900
parents
children 775dfe898662
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/CbC-examples/quicksort/quicksort_test.cbc	Tue Oct 13 17:15:58 2009 +0900
@@ -0,0 +1,99 @@
+#include<stdio.h>
+#include<stdlib.h>
+#include<assert.h>
+#include<unistd.h>
+
+#include"quicksort_test.h"
+
+void
+random_initialize(int *v, int size, int min, int max)
+{
+	int i;
+	int diff = max-min+1;
+
+	for (i=0; i<size; i++) {
+		v[i] = min+random()%diff;
+	}
+	return;
+}
+
+static void
+print_array(int *v, int size)
+{
+	int i;
+	printf("[");
+	for (i=0; i<size; i++) {
+		printf("%s%4d", (i%10==0)? "\n  ":" ", v[i]);
+	}
+	printf(" ]\n");
+}
+
+void
+starter()
+{
+	int *target;
+	int size=100;
+
+	target = (int*)malloc(sizeof(int)*size);
+	if (!target) {
+		perror("malloc");
+		exit(1);
+	}
+
+	random_initialize(target, size, 0, 90);
+
+	print_array(target, size);
+	goto quicksort(target, 0, size-1, exit0, (void*)target);
+
+	printf("bad region\n");
+}
+
+int
+main(int argc, char **argv)
+{
+	unsigned int seed=0;
+	int opt;
+
+	while ((opt = getopt(argc, argv, "s:")) != -1) {
+		switch (opt) {
+			case 's':
+				seed = atoi(optarg);
+				break;
+			default:
+				fprintf(stderr, "Usage: %s [-t times] [-n sizeofarray] [-s seed]\n", argv[0]);
+				exit(1);
+		}
+	}
+
+	srandom(seed);
+	starter();
+	return 0;
+}
+
+static int
+check_sort(int *v, int size)
+{
+	int i;
+	for (i=0; i<size-1; i++) {
+		if (v[i] > v[i+1])
+			return 0;
+	}
+	return 1;
+}
+
+__code
+exit0(void *arg)
+{
+	int *v = arg;
+	int b;
+	print_array(arg, 100);
+	b = check_sort(arg, 100);
+	if (b) {
+		printf("sorting successful!\n");
+		exit(-1);
+	} else {
+		printf("sorting failure! \n");
+		exit(0);
+	}
+}
+