因爲 js 沒有 C 語言的指針,因此咱們這裏模擬數組只是模擬數組操做的思路。數組
因爲本人水平有限,歡迎你們指正,看過能點個贊就更好了,謝謝你們。 bash
先建立一個ArrayList
類。app
class ArrayList {
list: any[]
length: number
constructor(list = []) {
this.list = list
this.length = list.length
}
}
複製代碼
從平時的使用中咱們可知,數組的push
方法是向數組最後一位添加元素,數組長度會變爲this.length + 1
,數組最後一位的數組下標爲 this.length
。因此咱們的新增方法能夠寫成:ui
appendChild(item: any) {
this.list[this.length] = item
this.length++
}
複製代碼
假定被刪除元素下標爲 i
this
this.list[i]
i
開始,this.list[i] = this.list[i + 1]
,元素被刪除,後面全部元素向前進一位。removeChild(index: number) {
let removeItem = this.list(index)
let length = this.length
// 從被刪除的元素開始向前移動
for (let i = index; i < length - 1; i++) {
this.list[i] = this.list[i + 1]
}
// 刪除最後一個空位
delete this.list[length - 1]
this.list.length--
this.length--
return removeItem
}
複製代碼
i,j
,對應須要反轉數組的頭尾i++, j--
i >= j
時,中止互換// 反轉
inversion(arys = null) {
let list = arys || this.list
let length = list.length - 1
// i 表明 頭, j 表明尾部下標
let i = 0, j = length - i, t: any;
while (j > i) {
t = list[i]
list[i] = list[j]
list[j] = t
i++
j--
}
return list
}
複製代碼
此方法有兩個參數,插入位置的下標以及被插入的元素。spa
this.list[length] = this.list[length - 1]
// 插入
insert(index: number, item: any) {
let length = this.length
// 從最後一位依次移動元素至被插入下標前一位
for (let i = length; i > index; i--) {
this.list[i] = this.list[i - 1]
}
this.list[index] = item
this.length++
return true
}
複製代碼
right
數組,小於基準值數放到left
數組right、left
數組,進行遞歸遍歷排序left
+ 基準值
+ right
組成的數組quicksort(arys, ) {
const ary = arys.slice(0)
if (ary.length <= 1) {
return ary
}
// 基準值下標
let pivotIndex = Math.floor(ary.length / 2);
基準值
let pivot = ary.splice(pivotIndex, 1);
const left = [], right = [];
for (let i = 0; i < ary.length; i++) {
//當前元素大於基準值
if (ary[i] > pivot) {
right.push(ary[i])
} else {
left.push(ary[i])
}
}
return this.quicksort(left).concat(pivot, this.quicksort(right))
}
複製代碼
歡迎你們進行指導留言,謝謝你們點贊鼓勵支持。 指針