js 데이터 구조 구현 - 더미 (최대 더미)
21301 단어 전단
/**
*
* @class
* @param {Array} [initDataArray]
* @param {number} [maxSize=9999]
*/
/**
* i=0, i , i (i-1)/2
*2*i+1 2*i+2
*/
function MaxHeap(initDataArray, maxSize = 9999) {
let arr=initDataArray || [];
let currSize=arr.length;
// heap,
let heap=new Array(arr.length);
function init() {
for(let i=0; i<currSize;i++){
heap[i]=arr[i];
}
//
let currPos=Math.floor((currSize-2)/2);
while (currPos>=0){
//
shif_down(currPos, currSize-1);
//
currPos--;
}
}
function shif_down(start,m) {
//
let parentIndex=start,
//
maxChildIndex=parentIndex*2+1;
while (maxChildIndex<=m){
if(maxChildIndex<m && heap[maxChildIndex]<heap[maxChildIndex+1]){
//
maxChildIndex=maxChildIndex+1;
}
if(heap[parentIndex]>=heap[maxChildIndex]){
break;
}else {
//
let temp=heap[parentIndex];
heap[parentIndex]=heap[maxChildIndex];
heap[maxChildIndex]=temp;
parentIndex=maxChildIndex;
maxChildIndex=maxChildIndex*2+1
}
}
}
/**
*
*
* @param {*} data
* @returns {boolean} isSuccess
*/
this.insert = function (data) {
//
if(currSize===maxSize){
return false
}
heap[currSize]=data;
shif_up(currSize);
currSize++;
return true;
};
function shif_up(start) {
let childIndex=start; //
let parentIndex=Math.floor((childIndex-1)/2); //
while (childIndex>0){
//
if(heap[parentIndex]>=heap[childIndex]){
break;
}else {
let temp=heap[parentIndex];
heap[parentIndex]=heap[childIndex];
heap[childIndex]=temp;
childIndex=parentIndex;
parentIndex=Math.floor((parentIndex-1)/2);
}
}
}
/**
* ,
*
* @returns {*} data
*/
this.removeRoot = function () {
if(currSize<=0){
return null;
}
let maxValue=heap[0];
heap[0]=heap[currSize];
currSize--;
shif_down(0, currSize-1);
return maxValue;
};
init();
}
/**
*
* @class
* @param {*} data
*/
function BinaryTreeNode(data) {
this.data = data;
this.parent = null;
this.leftChild = null;
this.rightChild = null;
}
const maxHeap = new MaxHeap();
const initDataArray = [];
for (let index = 0; index < 5; index++) {
const value = 5 + 95 * Math.random();
if (-1 === initDataArray.indexOf(value)) {
//
initDataArray.push(value);
if (!maxHeap.insert(value)) {
// ,
index--;
}
} else {
// ,
index--;
}
}
console.log('init array = ', initDataArray);
const max1 = maxHeap.removeRoot();
console.log('max1', max1);
const max2 = maxHeap.removeRoot();
console.log('max2', max2);
const max3 = maxHeap.removeRoot();
console.log('max3', max3);
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
전단 자동화 워 크 플 로 의 hooks예 를 들 어 우 리 는 git commt 전에 eslint 코드 검사, npm install 전에 프로젝트 의존 도 를 검사 하고 싶 습 니 다.전형 적 인 상황 에서 각종 도 구 는 특정한 동작 이 발생 할 때 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.