java版 2分查找
来源:互联网 发布:软件开发行业税率 编辑:程序博客网 时间:2024/05/02 04:58
/**
* 采用2分法实现有序数组的增删查
* 由于数组定义了大小就不能再改了 所以我们重新定义了size()方法;
* 将数据组成了一个对象
* @author leader
* 2009-11-3
*/
class Array
{
public static int maxsize ;//数组的长度的最大值
public static int realsize;
int [] array ;//数组
public Array (int maxsize)
{
//初始化这个类
this.maxsize = maxsize;
this.array = new int [this.maxsize];
this.realsize = 0 ;
}
/**
* 给数组添加数据
*/
public void insert (int ins)
{
//当数组还有空间的时候才能往里面插入数据
int len = this.realsize;
if(len == maxsize)
{
System.out.println("数组已满");
}
//由于是有序数组 所以要给新添加进来的数字放到排序后的位置
int i = 0;
for ( ;i<this.realsize;i++)
{
if(array[i]>ins)
{
//插入的数字小于数组中的某个成员的时候 就可以放在这个数字的前面 应为他是有序的排列的
break;
}
}
//讲这个数据以后的数据向后一位 从最后开始移
for (int j =this.realsize ;j>i;j--)
{
array[j] = array[j-1];
}
array[i]=ins;//将插入的数字放在正确的位置
this.realsize ++;//将数组长度加一
}
/**
* 数组的大小只是给人看的
* @return
*/
public int size ()
{
return this.realsize;
}
public void display ()
{
for (int i = 0 ;i<this.realsize;i++)
{
System.out.println(array[i]);
}
}
public void delete (int del)
{
int i = 0;
for ( ;i<this.realsize;i++)
{
if(array[i]==del)
{
break;
}
}
for(int j = i;j<this.realsize;j++)
{
array[j]=array[j+1];
}
this.realsize--;
}
/**
用二分法找数字
**/
public void find (int find)
{
int begin = 0;
int end = this.realsize;
while (true)
{
int tem = (begin+end)/2;
if(array[tem]<find)
{
begin = tem + 1;
}else if(array[tem]>find)
{
end = tem - 1;
}
else {
System.out.println("find it @ "+tem);
break;
}
}
}
}
public class Chape {
public static void main(String[] args) {
Array array = new Array(100);
array.insert(1);
array.insert(9);
array.insert(3);
array.insert(5);
array.insert(0);
array.delete(1);
array.display();
System.out.println("数组长度"+array.size());
array.find(9);
}
}
- java版 2分查找
- java 对分查找
- 2分法查找
- 2分查找
- 2分查找
- 2分查找算法
- 2分查找
- 2分查找
- 2分查找(折半查找)算法
- 数组-2分查找2
- 递归 2分查找法
- 《Java 编程技巧1001条》 第392条 了解2分查找
- 《Java 编程技巧1001条》 第393条 使用2分查找
- 算法-- 2分查找 Binary Search
- m 分查找
- 对分查找
- 对分查找
- 对分查找
- [转帖]Photoshop为外国美女黑白照片上色
- 关于ARM的22个常用概念--的确经典
- javascript跨域刷新父窗口并关闭当前窗口问题
- 让动态层(DIV)显示在YUI Chart上面
- 学习新得
- java版 2分查找
- 微软Bug管理(转载网址 http://hi.baidu.com/shan108/blog/item/90680b1f55bfba66f624e488.html)
- C#中使用多线程访问Winform问题解决方案
- embed 与 object
- JSP自定义标签(tag)
- 2410启动代码分析
- C#连接数据库和更新数据库
- 减小网络传输图片大小,使用gzip进行压缩
- Windows Mobile获取存储卡容量及使用情况