重拾算法-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、有序数组应用于查找频繁的情况。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值