xref: /titanic_51/usr/src/cmd/nscd/nscd_biggest.c (revision 8eea8e29cc4374d1ee24c25a07f45af132db3499)
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 (c) 1994 by Sun Microsystems, Inc.
24  * All rights reserved.
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 insertn(int * table, int n, int data)
51 {
52 	int size = *table;
53 	int guess, base, last;
54 	int olddata;
55 
56 	if (table[1] > n)
57 		return (data);
58 
59 	if (table[size] < n)  /* biggest so far */
60 		guess = size;
61 	else {
62 		base = 1;
63 		last = size;
64 		while (last >= base) {
65 			guess = (last+base)/2;
66 			if (table[guess] == n)
67 				goto doit;
68 			if (table[guess] > n)
69 				last = guess -1;
70 			else
71 				base = guess + 1;
72 		}
73 		guess = last;
74 	}
75 	doit:
76 	olddata = table[2 + size];
77 	memmove(table + 1, table+2, sizeof (int) * (guess-1));
78 	memmove(table + 2 + size, table + 3 + size, sizeof (int) * (guess-1));
79 	table[guess + size + 1] = data;
80 	table[guess] = n;
81 	return (olddata);
82 }
83 
84 /*
85  *  test code
86  */
87 #if 0
88 int
89 main(int argc, char * argv[])
90 {
91 	int * t;
92 	char buffer[100];
93 	int i, n;
94 	char * tmp;
95 
96 	t = maken(100);
97 
98 	for (i = 0; i < 1100; i++) {
99 		n = random();
100 		sprintf(buffer, "trial %d: %d", i, n);
101 		tmp = (char *)insertn(t, n, (int)strdup(buffer));
102 		if (tmp != -1) {
103 			printf("freeing %s\n", tmp);
104 			free(tmp);
105 		}
106 	}
107 
108 	for (i = 1; i <= 100; i++) {
109 		printf("%d: %s\n", i, t[100 + 1 + i]);
110 		free((char *)t[100 + 1 + i]);
111 	}
112 
113 	free(t);
114 }
115 #endif
116