有序數組和二分法查找

<span style="font-size:24px;">package com.liebao07;

public class OrdArr {
	private long[] a;
	private int nElements;
	public OrdArr(int max){
		a = new long[max];
		nElements = 0;
	}
	public int size(){
		return nElements;
	}
	
	public int find(long searchKey){
		int lowBound = 0;
		int upperBound = nElements-1;
		int currentIdx;
		while(true){
			currentIdx = (lowBound+upperBound)/2;
			if(a[currentIdx]==searchKey){
				return currentIdx;
			}else if(lowBound>upperBound){//can not found
				return nElements;//return size
			}else{
				if(a[currentIdx]<searchKey){
					lowBound = currentIdx+1;
				}else{
					upperBound = currentIdx-1;
				}
			}
		}
	}
	
	public void insert(long value){
		int j;
		for(j=0;j<nElements;j++){
			if(a[j]>value){
				break; 
			}
		}
		for(int k=nElements;k>j;k--){
			a[k] = a[k-1];
		}
		a[j] =value;
		nElements++;
	}
	
	public boolean delete(long value){
		int j = find(value);
		if(j==nElements){
			return false;
		}else{
			for(int k=j;k<nElements;k++){
				a[k] = a[k+1];
			}
			nElements--;
			return true;
		}
	}
	
	public void display(){
		for(int j=0;j<nElements;j++){
			System.out.print(a[j]+" ");
		}
		System.out.println();
	}
}</span>
<span style="font-size:24px;">測試用例:</span>
<span style="font-size:24px;"></span><pre name="code" class="java">package com.liebao07;

public class BinarySearchApp {
	public static void main(String[] args){
		int maxSize = 100;
		OrdArr arr ;
		arr = new OrdArr(maxSize);
		arr.insert(72);
		arr.insert(90);
		arr.insert(45);
		arr.insert(126);
		arr.insert(54);
		arr.insert(99);
		arr.insert(144);
		arr.insert(27);
		arr.display();
		int key = 27;
		if(arr.find(key)!=arr.size()){
			System.out.println("found "+key);
		}else{
			System.out.println("can not found "+key);
		}
		arr.delete(27);
		arr.delete(54);
		arr.display();
	}
}
輸出:
27 45 54 72 90 99 126 144 
found 27
45 72 90 99 126 144 

有序數組二分查找比較次數:

數據量 比較次數

10 4

100 7

1000 10

10000 14

100000 17

1000000 20

10000000 24

100000000 27

1000000000 30

優點:查找速度比無需數組快

缺點:插入時需要把後面的數據進行移動

與無序數組共同的缺點:刪除數據的時候需要把後面的數據往後面移動.

發佈了47 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章