數據結構與算法5

 二分法採用向下取整的方法數據庫

使用有序數組的好處是查找的速度比無序數組快的多,很差的方面是由於要將全部靠後的數據移開,因此速度較慢,有序數組和無序數組的刪除操做都很慢。數組

有序數組在查找頻繁的狀況下十分管用,但不適用於刪除和插入操做。因此適用於公司僱員的數據庫,查找頻繁,修改頻繁。數據結構

已知範圍,求出完成搜索的步驟,已知r,但願有一個方程能夠求出scode

s = log2(r)對象

class OrderArray {
private long[] a;
private int nElems;
public OrderArray(int max)
{
	a = new long[max];
	nElems = 0;
}
public int size()
{
return nElems;	
}
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;
		return curIn;
	}
		else
			upperBound = curIn - 1;
	}
}
}
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 = find(value);
	if(j == nElems)
		return false;
	else
	{
		for(int k=j;k<nElems;k++)
		a[k] = a[k+1];
		nElems--;
		return true;
	}
	}
	public void display(){
		for(int j=0;j<nElems;j++)
		System.out.print(a[j] + " ");
		System.out.println(" ");
	}
}
class OrderedApp{
	public static void main(String[] args)
	{
		int maxSize = 100;
		OrderArray arr;
		arr = new OrderArray(maxSize);
		arr.insert(77);
		arr.insert(99);
		arr.insert(44);
		arr.insert(55);
		arr.insert(22);
		arr.insert(88);
		arr.insert(11);
		arr.insert(00);
		arr.insert(66);
		arr.insert(33);		
		int searchkey = 55;
		if(arr.find(searchkey) != arr.size())
			System.out.println("found" + searchkey);
		else
			System.out.println("no found" + searchkey);
		arr.display();
		arr.delete(00);
		arr.delete(55);
		arr.delete(99);
		arr.display();
	}
}
found55
0 11 22 33 44 55 66 77 88 99  
11 22 33 66 77 88 99

存儲對象:class

數據結構中不光存儲long類型的簡單變量。存儲這些變量簡化了程序,可是對如何在現實中使用數據結構來講沒有表明性。一般咱們存儲的數據記錄是許多字段的結合。例如一條志願表由姓名,年齡等組成。變量

相關文章
相關標籤/搜索