顺序表
2016-04-07 19:11
281 查看
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)
优点:支持随机读取,以及空间利用率高
缺点:需要预先给出数组的最大数据元素个数,但数组的最大数据元素个数很难准确给出,另外,插入和删除操作时需要移动较多的数据元素
相关文章推荐
- CentOS中关于cannot find -lmysqlclient的解决
- Jquery动态删除添加表格中的内容
- 算法学习【6】寻找最小的k个,
- Spring中配置和读取多个Properties文件--转
- postgresql安装教程
- 凑算式
- solr入门之pinyin4j源码改写动态添加扩展词及整合进war项目中
- EL属性范围用法sessionScope等(转)
- 使用Cos组件实现文件的上传和下载
- 请在下列各项中,选出五项你认为是重要的
- sitemeth自定义模板
- MongoDB搭建副本集(一)
- JavaScript之语句
- Java参数传递,传递引用,传递值浅析
- 15电气李书鹏
- AtomicReference与volatile的区别
- [CQUOJ 21448] 会做题的兔兔 (数学+DP)
- lightOJ 1030(期望)
- linux系统安装
- Unity做AR