一 Java实现数组的的增删查。
public class HighArray { public long[] a; int nElem; public HighArray(int max){ a=new long[max]; nElem=0; } boolean delete (long searchkey){ int i; for( i=0;i<nElem;i++) if(a[i]==searchkey) break; if(i==nElem) return false; else{ for(int k=i;k<nElem-1;k++) a[k]=a[k+1]; nElem--; return true; } } boolean find (long searchkey){ int i; for(i=0;i<nElem;i++) if(searchkey==a[i]) break; if(i==nElem) return false; else return true; } void insert(long value){ a[nElem]=value; nElem++; } void display(){ int i; for(i=0;i<nElem;i++) System.out.print(a[i]+" "); System.out.println(); } } class HighArrayApp{ public static void main(String[]args){ HighArray array=new HighArray(5); array.insert(11); array.insert(22); array.insert(33); array.insert(44); array.insert(55); System.out.println(array.find(22)); array.display(); array.delete(11); array.display(); array.insert(66); array.display(); array.delete(44); array.delete(55); array.display(); } }
二 有序数据中二分查找的find()方法
long find (long searchkey){ int lowerBound=0; int upperBound=nElem-1; while (true){ int curIn = (lowerBound+upperBound)/2; if(a[curIn]==searchkey) return a[curIn]; else if(lowerBound>upperBound) return nElem; else { if (searchkey < a[curIn]) upperBound=curIn-1; else lowerBound=curIn+1; } } }
二分法查找查找次数及范围
设s为查找的次数,R为查找的范围,公式为:2s=R
s为步数 | R为范围 | 由2的幂表示的范围 |
0 | 1 | 20 |
1 | 2 | 21 |
2 | 4 | 22 |
3 | 8 | 23 |
4 | 16 | 24 |
5 | 32 | 25 |
6 | 64 | 26 |
7 | 128 | 27 |
8 | 256 | 28 |
9 | 512 | 29 |
10 | 1024 | 210 |