xref: /titanic_41/usr/src/cmd/nscd/nscd_biggest.c (revision fd9cb95cbb2f626355a60efb9d02c5f0a33c10e6)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <stdio.h>
30 #include <string.h>
31 #include <stdlib.h>
32 
33 /*
34  * routines to find largest n numbers, carrying 4 bytes of data
35  */
36 
37 int *
38 maken(int n)
39 {
40 	int * ret;
41 
42 	n++;
43 
44 	ret = (int *) memset(malloc(2 * n *sizeof (int)),
45 	    -1, 2 * n * sizeof (int));
46 	ret[0] = n - 1;
47 	return (ret);
48 }
49 
50 int
51 insertn(int * table, int n, int data)
52 {
53 	int size = *table;
54 	int guess, base, last;
55 	int olddata;
56 
57 	if (table[1] > n)
58 		return (data);
59 
60 	if (table[size] < n)  /* biggest so far */
61 		guess = size;
62 	else {
63 		base = 1;
64 		last = size;
65 		while (last >= base) {
66 			guess = (last+base)/2;
67 			if (table[guess] == n)
68 				goto doit;
69 			if (table[guess] > n)
70 				last = guess -1;
71 			else
72 				base = guess + 1;
73 		}
74 		guess = last;
75 	}
76 	doit:
77 	olddata = table[2 + size];
78 	memmove(table + 1, table+2, sizeof (int) * (guess-1));
79 	memmove(table + 2 + size, table + 3 + size, sizeof (int) * (guess-1));
80 	table[guess + size + 1] = data;
81 	table[guess] = n;
82 	return (olddata);
83 }
84 
85 /*
86  *  test code
87  */
88 #if 0
89 int
90 main(int argc, char * argv[])
91 {
92 	int * t;
93 	char buffer[100];
94 	int i, n;
95 	char * tmp;
96 
97 	t = maken(100);
98 
99 	for (i = 0; i < 1100; i++) {
100 		n = random();
101 		sprintf(buffer, "trial %d: %d", i, n);
102 		tmp = (char *)insertn(t, n, (int)strdup(buffer));
103 		if (tmp != -1) {
104 			printf("freeing %s\n", tmp);
105 			free(tmp);
106 		}
107 	}
108 
109 	for (i = 1; i <= 100; i++) {
110 		printf("%d: %s\n", i, t[100 + 1 + i]);
111 		free((char *)t[100 + 1 + i]);
112 	}
113 
114 	free(t);
115 }
116 #endif
117