顺序表

class SeqList{
    private int maxSize;
    private int size;
    private Object[] listArray;

    //构造函数
    public SeqList(int size){
        maxSize = size;
        listArray = new Object[size];
        size = 0;
    }

    //插入
    public void insert(int index,Object obj) throws Exception{
        if(size == maxSize){
            throw new Exception("顺序表已满无法插入!");
        }
        if(index<0 || index>size){
            throw new Exception("参数错误!");
        }
        for(int j=size;j>index;j--){
            listArray[j] = listArray[j-1];
        }
        listArray[index] = obj;
        size++;
    }

    //删除
    public Object delete(int index) throws Exception {  

        if(size == 0){
            throw new Exception("链表为空无法删除!");
        }

        if(index<0 || index>size-1){
            throw new Exception("参数有误!");
        }

        Object it = listArray[index];
        for(int j=index;j<size-1;j++){
            listArray[j] = listArray[j+1];
        }

        size--;
        return it;
    }

    //获取元素
    public Object getData(int index) throws Exception { 
        if(index<0 || index>size-1){
            throw new Exception("参数有误!");
        }
        return listArray[index];
    }

    //获取元素个数
    public int size() { 
        return size;
    }

    //是否为空
    public boolean isEmpty() {  
        return size == 0;
    }

}

//测试类
public class Demo{
    public static void main(String[] args) {
        try {
            SeqList seqList = new SeqList(3);
            seqList.insert(0, new Integer(1));
            seqList.insert(1, new Integer(2));
            seqList.insert(2, 3);
            System.out.println(seqList.isEmpty());
            System.out.println("listArray[1] = "+seqList.getData(1));
            System.out.println("listArray[2] = "+seqList.getData(2));
            System.out.println("size = "+seqList.size());
            System.out.println("delete listArray[0] = "+seqList.delete(0));
        } catch (Exception e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
    }
}

运行结果:

false
listArray[1] = 2
listArray[2] = 3
size = 3
delete listArray[0] = 1


效率分析

在顺序表中插入一个数据元素时,主要耗时的是循环移动数据元素部分。最坏情况是index = 0,需移动size个数据元素;最好情况是index = size,需移动0个数据元素;平均次数为 n/2

在顺序表中删除一个数据元素时,主要耗时的是循环移动数据元素部分。最坏情况是index = 0,需移动size-1个数据元素;最好情况是index = size,需移动0个数据元素;平均次数为 (n-1)/2

顺序表其他操作都和数据元素个数n无关,因此,插入和删除函数的时间复杂度为O(n)

顺序表支持随机读取,因此,读取函数的时间复杂度为O(1)


优点:支持随机读取,以及空间利用率高

缺点:需要预先给出数组的最大数据元素个数,但数组的最大数据元素个数很难准确给出,另外,插入和删除操作时需要移动较多的数据元素




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值