Data structure and algorithm 5

Keywords: Database

Dichotomy adopts the method of rounding down

The advantage of using ordered array is that the speed of searching is much faster than that of unordered array. The disadvantage is that it needs to move all the backward data away, so the speed is slow. The deletion of ordered array and unordered array is very slow.

Ordered arrays are very useful in frequent lookups, but they are not suitable for delete and insert operations. Therefore, it is applicable to the database of company employees, which is frequently searched and modified.

Given the range, find out the steps to complete the search, known r, hope to have an equation to find s

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  

Storage object:

Data structure not only stores simple variables of long type. Storing these variables simplifies the program, but is not representative of how to use data structures in reality. Usually the data records we store are a combination of many fields. For example, a volunteer form consists of name, age, etc.

Posted by Andre_Ng on Fri, 31 Jan 2020 08:54:12 -0800