public class OrderedArray { private int numElements = 0; private int[] elements; // Constructor..Note: the caller has to provide the array of elements. // This is because Java generics do not allow a call "elements = new T[100]". // public OrderedArray(int[] elts) { elements = elts; } public int getNumElements() { return numElements; } public int nth(int n) { // return the Nth element if (n < numElements) return elements[n]; else return -1; } public int first() { return nth(0); } public int last() { return nth(numElements-1); } // search(X) returns the index where X is, if X is in the list. // Otherwise, it returns the index of the smallest number greater than X public int search(int x) { if (numElements==0) return 0; if (x <= first()) return 0; if (x > last()) return numElements; if (x == last()) return numElements-1; return search1(x,0,numElements-1); } // X is strictly between L and U. public int search1(int x,int l,int u) { if (u==l+1) return u; else { int m = (l+u)/2; if (x==elements[m]) return m; else if (x < elements[m]) return search1(x,l,m); else return search1(x,m,u); } } public boolean inList(int x) { return (elements[search(x)]==x); } public void add(int x) { int i = search(x); if (elements[i] != x) { for (int j = numElements; j>i; j--) elements[j]=elements[j-1]; elements[i]=x; numElements++; } } public void delete(int x) { int i = search(x); if (elements[i] == x) { for (int j=i+1; j < numElements; j++) elements[j-1] = elements[j]; numElements--; } } public String toString() { String s = "["; for (int i=0; i < numElements; i++) s = s + " " + elements[i]; return s+"]"; } public static void main(String[] args) { OrderedArray l = new OrderedArray(new int[100]); l.add(31); l.add(41); l.add(59); l.add(26); l.add(53); l.add(58); l.add(37); l.delete(53); System.out.println(l.toString()); System.out.println(l.search(2)); System.out.println(l.search(26)); System.out.println(l.search(53)); System.out.println(l.search(54)); System.out.println(l.search(195)); } }