import java.util.Arrays;
/**
* Created with Intellij IDEA
* ClassName:MyArrayList
* User:MaLe
* Description:实现顺序表的各种方法
* @Date:2021/10/21
* @Time:9:25
* @author:395645313@qq.com
*/
public class MyArrayList {
public int[] elem;//null
public int usedSize;
public MyArrayList() {
this.elem = new int[10];
}
// 打印顺序表
public void display() {
for (int i = 0; i < this.usedSize; i++) {
System.out.print(this.elem[i]+" ");
}
System.out.println();
}
// 在 pos 位置新增元素
public void add(int pos, int data) {
int i=usedSize-1;
if (pos<0 || pos>this.usedSize){
System.out.println("pos位置不合法");
return;
}
//2倍扩容
if (this.elem.length==this.usedSize){
this.elem= Arrays.copyOf(this.elem,this.elem.length*2);
}
while (i>=pos){
this.elem[i+1]=this.elem[i]; //挪开元素
}
this.elem[pos]=data; //插入元素
usedSize++;
}
// 判定是否包含某个元素
public boolean contains(int toFind) {
int i=0;
int j=this.usedSize-1;
while (j>i){
int mid=(j+i)/2;
if (this.elem[mid]>toFind){
j=mid-1;
}
else if (this.elem[mid]<toFind){
i=mid+1;
} else {
return true;
}
}
return false;
}
// 查找某个元素对应的位置
public int search(int toFind) {
for (int i = 0; i < this.usedSize; i++) {
if (elem[i] == toFind) {
return i;
}
}
return -1;
}
//判断顺序表是否为空
public boolean isEmpty() {
return this.usedSize==0;
}
// 获取 pos 位置的元素
public int getPos(int pos) {
if (this.usedSize<=pos || pos<0){
System.out.println("不合法输入");
return -1;
}
return this.elem[pos];
}
// 给 pos 位置的元素设为 value
public void setPos(int pos, int value) {
if (pos<0 || pos>usedSize){
throw new ArrayIndexOutOfBoundsException("pos位置不合法");
}
this.elem[pos] = value;
}
//删除第一次出现的关键字key
public void remove(int toRemove) {
if (isEmpty()){
System.out.println("顺序表为空");
return;
}
int index=search(toRemove);
if (index==-1){
System.out.println("没有找到数字:"+toRemove);
return;
}
for (int i = index; i <usedSize-1; i++) {
this.elem[i] = this.elem[i + 1];
}
this.usedSize--;
}
// 获取顺序表长度
public int size() {
return this.usedSize;
}
// 清空顺序表
public void clear() {
for (int i = 0; i <this.usedSize; i++) {
this.elem[i]=0;
}
this.usedSize=0;
}
public static void main(String[] args) {
MyArrayList my=new MyArrayList();
my.add(0,11);
my.add(1,54);
my.add(2,65);
my.add(3,78);
my.display();
System.out.println(my.contains(65));
System.out.println(my.contains(66));
System.out.println(my.search(65));
System.out.println(my.getPos(3));
my.setPos(0,22);
my.display();
my.remove(22);
my.display();
System.out.println(my.size());
}
}