【DataStructure&AlgorithmInJava】Ch02-OrderArray w binarySearch
来源:互联网 发布:mysql 添加触发器 编辑:程序博客网 时间:2024/06/06 12:42
class OrderArray{private int nElems;private int[] arr;public OrderArray(int size){arr=new int[size];nElems=0;}//------***insert for ordered array----------------------------------public void insert(int value){//----plz remember clearly!------int i;for(i=0;i<nElems;i++)//find the slotif (value < arr[i]) //----note:<----break;for(int k=nElems;i<k;k--) //move larger elementsarr[k]=arr[k-1]; //---note: other loop methods are easy to make an Exception!arr[i]=value;// just remember it;nElems++;//---**--}//-----delete-------public boolean delete(int value){//---note:return boolean--int i=binarySearch(value);if (i==-1)return false;else{for(int k=i;k<nElems;k++)arr[k]=arr[k+1]; //---index out of boundry, problem? nElems--;return true;}}//-----binarySearch----public int binarySearch(int key){int lowerB=0;int upperB=nElems-1;int mid;while(true){mid=(lowerB+upperB)/2;if (arr[mid]==key)return mid;else if (lowerB>upperB)return -1;else{if (key<arr[mid])upperB=mid-1;else lowerB=mid+1;}}}//-----get length()----public int getLength(){return nElems;}//-----print-----public void print(){for(int i=0;i<nElems;i++)System.out.println("arr["+i+"]="+arr[i]);}}class OrderArrayDemo{public static void main(String[] args){int maxSize=100;OrderArray arr=new OrderArray(maxSize);arr.insert(7);arr.insert(1);arr.insert(13);arr.insert(110);arr.insert(10);arr.print();System.out.println("array length="+arr.getLength());arr.delete(110);arr.print();System.out.println("array length="+arr.getLength());System.out.println("index of 10 is:"+arr.binarySearch(10));arr.print();}}
0 0
- 【DataStructure&AlgorithmInJava】Ch02-OrderArray w binarySearch
- 【DataStructure&AlgorithmInJava】Ch02-HighArrayDemo
- 【DataStructure&AlgorithmInJava】Ch02-BinarySearchDemo
- 【DataStructure&AlgorithmInJava】Ch02-PersonArrayDemo
- 【DataStructure&AlgorithmInJava】Ch05-LinkedListDemo1
- Ch02
- BinarySearch
- BinarySearch
- binarySearch
- BinarySearch
- BinarySearch
- BinarySearch
- BinarySearch
- ch02:进程
- ch02 hello
- useful datastructure:
- All DataStructure
- Game - datastructure
- 数据结构:栈
- IE 中 atl控件 不使用连接点回调javascript函数
- 数据结构:队列
- python beautifulsoup
- Ubuntu下配置Tomcat以指定(非root)身份运行
- 【DataStructure&AlgorithmInJava】Ch02-OrderArray w binarySearch
- Codeforces Round #244 (Div. 2)
- hadoop distributed cache
- 对javaBean的理解
- 美利坚西行记(2):行前准备工作-“行”
- 最大匹配算法
- 扯谈网络编程之自己实现ping
- 使用FragmentTabHost时,tabwidget被frament覆盖。
- 我国化肥全世界密度最高,土壤破坏厉害