下面的内容都是透过java学习数据结构(或者说是互相渗透):
java的一个思想是可以让很多客户都用到一个很成熟的类(比如说数组,字符串),我们进行增,删,查,改时,不需要知道他是怎么做的,只需要知道他是做什么的(调用类的方法),这就是接口,比如下面的代码(通过一个类来提供接口):
public class Ha //通过编写一个类实现数组的查找等功能,面向
{ //对象编程最重要的优点之一就是可以使接口
private long[] a; //变得简单,高效
int elem;
public Ha(int max)
{
a=new long[max];
elem=0;
}
//------------------------------------
public boolean find(long value)
{
int j;
for(j=0;j<elem;j++)
if(a[j]==value) break;
if(j==elem) return false;
else return true;
}
//------------------------------------
public void inset(long value_2)
{
a[elem]=value_2;
elem++;
}
//------------------------------------
public boolean del(long value_3)
{
int j;
for(j=0;j<elem;j++)
if(a[j]==value_3) break;
if(j==elem) return false;
else {
for(int k=j;k<elem;k++)
a[k]=a[k+1];
elem--;
return true;
}
}
//------------------------------------
public void p()
{
for(int j=0;j<elem;j++)
System.out.print(a[j]+" ");
System.out.println();
}
//------------------------------------
}
再你使用的时候在创建一个类调用它抽象给你的接口(函数名):
public class Ca
{
public static void main(String[] args)
{
Ha a=new Ha(100);
a.inset(1);
a.inset(2);
a.inset(3);
a.inset(4);
a.inset(5);
a.p();
a.del(3);
a.p();
if(!a.find(3)) System.out.println("false find this number!");
}
}
这样就不要像C一样,进行过程式的编写程序,直接通过已有的接口去进行编程,需要注意的是static函数不能调用非static的变量及函数,除非实例化对象,通过对象.成员;进行调用;客户甚至不清楚数据是通过什么数据结构存储的,结构被隐藏在了接口之后。
上面进行查找find()是通过线性查找的,而一种更高效的二分查找:
public int find_2(long value_4)
{
int low=0;
int high=elem-1;
int cur;
while(1)
{
cur=(low+high)/2;
if(a[cur]==value_4) return cur;
else if(low>high) return -1;
else {
if(a[cur]<value_4) low=cur+1;
else high=cur-1;
}
}
}
线性查找的时间是O(N)的话,二分查找的时间为O(logN)。