1、概述
觉得对于下标,搞清楚size的位置很有必要
2、查
遍历数组,大小size,查key
public static int findByElement(int[] arr, int size, int key){
for (int i = 0; i < size; i++) {
if( arr[i] == key){
return i;
}
}
return -1;
}
3、增
index = size的原因:
主要是针对末尾插入
不设为0或size - 1的原因是当数组元素没一个比element大时(即在末尾插的时候), 后续循环对于插入位置的index是不会改变的,此时就需要以默认值插入, 而对于中插和头插,index初始值赋多少都无所谓,因为后续循环会更改index下标值
public static int addByElementSequence(int[] arr, int size, int element){
//数组是满的,没有空间继续添加了
if(size >= arr.length){
throw new IllegalArgumentException("Add failed. Array is full");
}
//不设为0或size - 1的原因是当数组元素没一个比element大时(即在末尾插的时候),
//后续循环对于插入位置的index是不会改变的,此时就需要以默认值插入
//而对于中插和头插,index初始值赋多少都无所谓,因为后续循环会更改index下标值
int index = size;
//找到待插入位置
for (int i = 0; i < size; i++) {
if(element < arr[i]){
index = i;
break;
}
}
//元素往后移
for (int j = size; j > index; j--) {
arr[j] = arr[j-1];
}
//插入元素
arr[index] = element;
return index;
}
4、删
对于头删,中删,会执行所有的循环
对于尾删,前移的循环不执行,只size--,输出时,只是下标0到size-1的部分
对于要删除的元素在数组中不存在(没查到),则size不变,没有删任何值,直接返回size
public static int removeByElement(int[] arr, int size, int key){
int index = -1;
//查元素
for (int i = 0; i < size; i++) {
if(key == arr[i]){
index = i;
break;
}
}
//能查到
if(index != -1){
//前移
for(int i = index + 1; i < size; i++)
arr[i-1] = arr[i];
//长度-1
size--;
}
return size;
}