summaryrefslogtreecommitdiff
path: root/stdlib/tst-qsort2.c
blob: 75d4a1732dd00e5e599fdcb96ac8e8d3bfcaa207 (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
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <stdio.h>
#include <stdlib.h>

char *array;
char *array_end;
size_t member_size;

int
compare (const void *a1, const void *b1)
{
  const char *a = a1;
  const char *b = b1;

  if (! (array <= a && a < array_end
	 && array <= b && b < array_end))
    {
      puts ("compare arguments not inside of the array");
      exit (EXIT_FAILURE);
    }
  int ret = b[0] - a[0];
  if (ret)
    return ret;
  if (member_size > 1)
    return b[1] - a[1];
  return 0;
}

int
test (size_t nmemb, size_t size)
{
  array = malloc (nmemb * size);
  if (array == NULL)
    {
      printf ("%zd x %zd: no memory", nmemb, size);
      return 1;
    }

  array_end = array + nmemb * size;
  member_size = size;

  char *p;
  size_t i;
  size_t bias = random ();
  for (i = 0, p = array; i < nmemb; i++, p += size)
    {
      p[0] = (char) (i + bias);
      if (size > 1)
	p[1] = (char) ((i + bias) >> 8);
    }

  qsort (array, nmemb, size, compare);

  for (i = 0, p = array; i < nmemb - 1; i++, p += size)
    {
      if (p[0] < p[size]
	  || (size > 1 && p[0] == p[size] && p[1] < p[size + 1]))
	{
	  printf ("%zd x %zd: failure at offset %zd\n", nmemb,
		  size, i);
	  free (array);
	  return 1;
	}
    }

  free (array);
  return 0;
}

int
main (int argc, char **argv)
{
  int ret = 0;
  if (argc >= 2)
    ret |= test (atoi (argv[1]), atoi (argv[2]));
  else
    {
      ret |= test (10000, 1);
      ret |= test (200000, 2);
      ret |= test (2000000, 3);
      ret |= test (2132310, 4);
      ret |= test (1202730, 7);
      ret |= test (1184710, 8);
      ret |= test (272710, 12);
      ret |= test (14170, 32);
      ret |= test (4170, 320);
    }

  return ret;
}