重拾算法-01、JAVA有序數組封裝(包含二分法查詢,插入,刪除)

package com.lxl.array.pojo;

/**
 * 有序數組對象封裝
 * @author xiaole
 *
 */
public class OrdArray {
	private int[] a;
	
	private int nElems;// 數據實際長度
	
	public OrdArray(int a) {
		this.a = new int[a];
		this.nElems = 0;
	}
	
	public int size() {
		return nElems;
	}
	
	public int find(int searchKey) {
		int start = 0;
		int end = nElems;
		int curIn;
		
		while(true) {
			curIn = (start + end) / 2;
			if (a[curIn] == searchKey)
				return curIn;
			else if (start > end)
				return nElems; // 未找到
			else {
				if (a[curIn] > searchKey)
					end = curIn - 1;
				else
					start = curIn + 1;
			}
		}
	} 
	
	public void insert (int 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 (int value) {
		int find = find(value);
		if (find == nElems)
			return false;
		else {
			for (int k = find; k < nElems-1; k++)
				a[k] = a[k+1];
			nElems--;
			return true;
		}
	}

	public void display() {
		for (int i = 0; i < nElems ;i++)
			System.out.println(a[i]);
	}
	
}

1、有序數組的好處,查找速度可以使用二分法,比無序數組快得多。

2、有序數組的壞處,插入操作是需要對所有靠後的數據進行移動,速度較慢。

3、無序數組與有序數組,刪除操作因爲都要有前移的操作,所以都很慢。

4、有序數組應用於查找頻繁的情況。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章