Heap and Heapsort

heap data structure

Max heap: is a complete binary tree, all child nodes are not greater than the parent node

The smallest pair: is a complete binary tree, all child nodes are not smaller than the parent node

Stored in an array: i's parent node is Math.floor(i/2)

The left child of i is 2*i

The right child of i is 2*i+1

Store values ​​starting at 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 }

binary search

For ordered sequential lists only

 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 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325090548&siteId=291194637