01: /*
02: * @(#)binarySearch.java 1.2 04/12/06
03: *
04: * Copyright (c) 2004 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package org.pnuts.lib;
10:
11: import pnuts.lang.Context;
12: import pnuts.lang.PnutsFunction;
13: import java.util.List;
14: import java.util.Arrays;
15: import java.util.Collections;
16:
17: public class binarySearch extends PnutsFunction {
18:
19: public binarySearch() {
20: super ("binarySearch");
21: }
22:
23: public boolean defined(int narg) {
24: return narg == 2;
25: }
26:
27: protected Object exec(Object[] args, Context context) {
28: if (args.length != 2) {
29: undefined(args, context);
30: return null;
31: }
32: Object elements = args[0];
33: Object key = args[1];
34: if (elements instanceof List) {
35: return new Integer(Collections.binarySearch(
36: (List) elements, key, new PnutsComparator(context)));
37: } else if (elements instanceof Object[]) {
38: return new Integer(Arrays.binarySearch((Object[]) elements,
39: key, new PnutsComparator(context)));
40: } else if (elements instanceof int[]) {
41: return new Integer(Arrays.binarySearch((int[]) elements,
42: ((Number) key).intValue()));
43: } else if (elements instanceof byte[]) {
44: return new Integer(Arrays.binarySearch((byte[]) elements,
45: ((Number) key).byteValue()));
46: } else if (elements instanceof char[]) {
47: return new Integer(Arrays.binarySearch((char[]) elements,
48: ((Character) key).charValue()));
49: } else if (elements instanceof short[]) {
50: return new Integer(Arrays.binarySearch((short[]) elements,
51: ((Number) key).shortValue()));
52: } else if (elements instanceof long[]) {
53: return new Integer(Arrays.binarySearch((long[]) elements,
54: ((Number) key).longValue()));
55: } else if (elements instanceof float[]) {
56: return new Integer(Arrays.binarySearch((float[]) elements,
57: ((Number) key).floatValue()));
58: } else if (elements instanceof double[]) {
59: return new Integer(Arrays.binarySearch((double[]) elements,
60: ((Number) key).doubleValue()));
61: } else {
62: throw new IllegalArgumentException(String.valueOf(elements));
63: }
64: }
65:
66: public String toString() {
67: return "binarySearch(elements, key)";
68: }
69: }
|