最大堆:是一個徹底二叉樹,全部子節點都不大於父節點數組
最小對:是一顆徹底二叉樹,全部子節點都不小於父節點數據結構
用數組存儲:i的父節點是Math.floor(i/2)spa
i的左孩子節點是2*icode
i的右孩子節點是2*i+1blog
從index=1開始存儲值get
1 let maxHeap = { 2 heap:[], 3 heapPop:function(){ 4 let del = maxHeap.heap[1]; 5 maxHeap.heap[1] = maxHeap.heap[maxHeap.heap.length-1]; 6 maxHeap.heap.length--; 7 let k = 1; 8 while(2*k <= maxHeap.heap.length -1){ 9 let j = 2*k; // heap[j]與heap[k]交換 10 if(j+1 < maxHeap.heap.length -1 && maxHeap.heap[j+1] > maxHeap.heap[j]){ 11 j++; 12 } 13 if(maxHeap[k] >= maxHeap[j]){ 14 break; 15 } 16 let tmp = maxHeap.heap[k]; 17 maxHeap.heap[k] = maxHeap.heap[j]; 18 maxHeap.heap[j] = tmp; 19 k = j; 20 } 21 console.log(maxHeap.heap); 22 return del; 23 }, 24 heapPush:function(item){ 25 maxHeap.heap[maxHeap.heap.length+1] = item; 26 let k = maxHeap.heap.length; 27 while(k > 1 && maxHeap.heap[Math.floor(k/2)] < maxHeap.heap[k]){ 28 let tmp = maxHeap.heap[k]; 29 maxHeap.heap[k] = maxHeap.heap[Math.floor(k/2)]; 30 maxHeap.heap[Math.floor(k/2)] = tmp; 31 k = Math.floor(k/2); 32 } 33 return maxHeap.heap; 34 }, 35 36 37 }
僅用於有序的順序表it
1 function binarySearch(arr,target){ 2 let low = 0, 3 high = arr.length - 1, 4 mid = Math.floor((low+high)/2); 5 while(low <= high){ 6 if(arr[mid] === target){ 7 return mid; 8 } 9 if(target < arr[mid]){ 10 high = mid - 1; 11 }else{ 12 low = mid + 1; 13 } 14 } 15 return false; 16 }