數組_有序數組
阿新 • • 發佈:2017-12-22
system args while ems 有序 class lean [] let
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(); } }
數組_有序數組