public class OrdArray { private long[] a; private int nElems; public OrdArray(int maxSize) { a=new long[maxSize]; nElems=0; } public int size() { return nElems; } //有序数组的插入(需要找到位置) public void insert(long value) { int j; for(j=0;j<nElems;j++) if(a[j]>value) break; //挪出位置 for(int k=nElems;k>j;k--) a[k]=a[k-1]; a[j]=value; nElems++; } public boolean delete(long value) { int j; for(j=0;j<nElems;j++) if(a[j]==value) break; if(j==nElems) return false; else for(int k=j;k<nElems;k++) a[k]=a[k+1]; nElems--; return true; } //用二分查找方式找到位置,删除数据 public boolean findDelete(long value) { int j=find(value); if(j==nElems) return false; else for(int k=j;k<nElems;k++) a[k]=a[k+1]; nElems--; return true; } //二分查找 public int find(long searchKey) { int lowerBound=0; int upperBound=nElems-1; int curIn; while(true) { curIn=(lowerBound+upperBound)/2; if(a[curIn]==searchKey) return curIn; else if(lowerBound>upperBound) return nElems;//没有找到,返回数据总量 else { if(a[curIn]<searchKey) lowerBound=curIn+1; else upperBound=curIn-1; } } } public void display() { for(int j=0;j<nElems;j++) System.out.print(a[j]+" "); System.out.println(); } }
public class Test { public static void main(String[] args) { int maxSize=100; OrdArray array; array=new OrdArray(maxSize); array.insert(77); array.insert(99); array.insert(44); array.insert(55); array.insert(22); array.insert(88); array.insert(11); array.insert(00); array.insert(66); array.insert(33); if(array.find(55)!=array.size()) System.out.println("found"); else System.out.println("no found"); array.display(); array.findDelete(00); array.findDelete(55); array.findDelete(99); array.display(); } }
时间: 2024-10-30 00:07:07