堆和堆排序
堆数据结构
最大堆:是一个完全二叉树,所有子节点都不大于父节点
最小对:是一颗完全二叉树,所有子节点都不小于父节点
用数组存储:i的父节点是Math.floor(i/2)
i的左孩子节点是2*i
i的右孩子节点是2*i+1
从index=1开始存储值
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 }
仅用于有序的顺序表
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 }