线性表 - 无序表
getItem O(1)
setItem O(1)
push O(n)
insert O(n)
delect O(n)
search O(n)
基本操作
class List {
// 1.创建空的数组 指定size
constructor() {
this.arr = new Array(10);
this.size = 10;
this.length = 0;
this.realloc = () => {
let new_arr = null;
// 扩大
if(this.length === this.size) {
// 增加空间 原来数据拷贝到新数据
this.size = this.size*2;
new_arr = new Array(this.size);
} else if(this.length < (this.size/4)) {
// 判断是否需要缩小
this.size = Math.floor(this.size/2);
new_arr = new Array(this.size);
}
if(new_arr) {
for(let i = 0; i < this.length; i++){
new_arr[i] = this.arr[i]
}
delete this.arr;
this.arr = new_arr;
}
};
this.checkRange= (index) => {
if(typeof index !== 'number' || index < 0 || index >= this.length) {
throw new RangeError();
}
}
}
getItem(index){
this.checkRange(index);
return this.arr[index];
}
setItem(index, value) {
this.checkRange(index);
return this.arr[index] = value;
}
// 添加
append(value){
this.arr[this.length] = value;
this.length++;
// 如果超出 扩展空间
this.realloc();
}
// 插入
insert(value, pointIndex) {
if(pointIndex < 0 || pointIndex > this.length) {
throw new RangeError();
} else if (pointIndex === this.length) {
append(value);
} else {
// 1.index的数据都向后移动一位
for(let j = this.length; j > pointIndex; j --) {
this.arr[j] = this.arr[j-1];
}
// 2.新的数据放到 index 位置上
this.arr[pointIndex] = value;
this.length++;
// 如果超出 扩展空间
this.realloc();
}
}
// 删除某一项
delete(index) {
this.checkRange(index);
// 1.index的数据都向前移动一位
for(let j = index; j < this.length -1; j ++) {
this.arr[j] = this.arr[j+1];
}
this.length--;
this.realloc();
}
// 有序的数组 二分法查找 适用于搜索性能更高
search(value) {
let s = 0;
let e = this.arr.length - 1;
while(s <= e) {
let center = Math.floor((s+e)/2);
if(value === this.arr[center]) {
return center;
} else if(value < this.arr[center]) {
e = center - 1;
} else(value > this.arr[center]) {
s = center + 1;
}
}
return -1;
}
}
const list = new List();
list.append(1);
list.append(2);
list.append(3);
list.append(4);
list.append(5);
list.append(6);
list.append(7);
list.append(8);
list.append(9);
list.append(10);
list.append(6);
list.append(7);
list.append(8);
list.append(9);
list.append(10);
list.append(11);
console.log(list);