数组是线性表。连续的内存空间、存储相同的数据类型。
一般从0开始编号,因为下标确切代表着偏移量。
优点:可以实现随机访问。缺点:删除、插入操作低效。
插入操作:数组有序,复杂度为(1+2+...+n)/n=O(n)。如果无序,可以直接将原本位置k的元素直接移到最后,再将要插入的元素放到k处。
删除操作:若依次搬移,则复杂度为O(n)。但是在某些场景下,可以将多次删除一次进行,类似于JVM中的标记清除垃圾回收算法。
容器Array List:可以将操作细节进行封装,支持动态扩容,不够时会自动扩充为1.5倍。
ArrayList无法存储基本类型,需要将基本类型封装为Integer、Long等引用类型,有性能消耗。
//实现数组的插入、删除、按照下标随机访问操作
//数组中的数据是int型的
public class Array {
//定义整型数据data保存数据
public int data[];
//定义数组长度
private int n;
//定义实际个数
private int count;
//构造方法,定义数组大小
public Array(int capacity){
this.data = new int[capacity];
this.n = capacity;
this.count=0;
}
//根据索引,找到数据中的元素并返回
public int find(int index){
if(index<0 || index>=count){
return -1;
}
return data[index];
}
//插入元素
public boolean insert(int index,int value){
//数组中无元素
if(index==count&&count==0){
data[index] =value;
++count;
return true;
}
if(index<0 || index>count){
System.out.println("输入位置不合法");
return false;
}
if(count == n){
System.out.println("数组已满");
return false;
}
//位置合法
for(int i=count;i>index;--i){
data[i] = data[i-1]; //index之后的元素统统右移
}
data[index] =value;
++count;
return true;
}
//根据索引删除数组中的元素
public boolean delete(int index){
if(index<0 || index>=count){
System.out.println("输入位置不合法");
return false;
}
for(int i=index+1;i<count;i++){
data[i-1]=data[i]; //从index+1之后的元素往前移
}
--count;
return true;
}
//遍历数组
public void printAll(){
for(int i=0;i<count;i++){
System.out.println(data[i] + "");
}
}
public static void main(String[] args){
Array array = new Array(5);
array.insert(0,3);
array.insert(1,4);
array.insert(2,5);
array.find(1);
//array.delete(2);
array.printAll();
}
}