"Introduction to Algorithms" @书Note@ Chapter 6-Heap Sorting (including js version code implementation)

What is heap sort

Heap (English: heap) is a general term for a special type of data structure in computer science. The heap is usually an array object that can be seen as a tree. The heap always satisfies the following properties:

  • The value of a node in the heap is always not greater than or not less than the value of its parent node;
  • Heap is always a complete binary tree.


In javascript, we use arrays to implement this data structure.
Heap sorting uses this data structure for sorting.

Algorithm ideas

It is to create a maximum heap, and then use the top of the heap to always be the largest value for sorting.As
shown in the figure below, the value of the yellow area (top of the heap) and the value of the pink area (the last bit) are exchanged each time,

and the last bit is excluded. Reshape the largest heap in the array below,
so back and forth, to this heap only one element is left to complete the entire sorting process

Algorithm process

  1. First define a sorting method HeapSort
  2. Then we need to build a maximum heapBuildMaxHeap
  3. Then we need a way to maintain the nature of the heap, that is, to reshape the heap methodMaxHeap
  4. Swap positions from the top of the heap to the end of the array and reshape

BuildMaxHeapThe premise is that we must first treat the array as a heap. After seeing it as a heap, we need to know the relationship between the position in the array and the position of the heap. As shown in the figure below,

we start with the bottom of the heap to MaxHeapbuild the largest heap. It
MaxHeapis assumed that there is one Heap, the left and right nodes on the top of the heap are in line with the nature of the largest heap

Algorithm implementation

/**
 * 时间复杂度 平均:O(nlog2n)。
 * 空间复杂度:O(1)。
 * 稳定性:不稳定
 */

function HeapSort(arr) {
    
    
	var len = arr.length;
	BuildMaxHeap(arr,len);
	for (var i = len-1 ; i > 0; i--) {
    
    
		let box = arr[0];
		arr[0] = arr[i];
		arr[i] = box;
		MaxHeap(arr,0,i);
	}
	return arr
}

function MaxHeap(arr,i,length) {
    
    
	var largest = null;
	var node = arr[i]; //保存当前节点
	var left = i * 2 + 1 ; //定位节点左
	var right = i * 2 + 2; //定位节点右	
	//判断当前有这个节点 (这里会存在当前这个的子节点不存在的情况)处理一下边界情况
	if (left < length && node < arr[left]) {
    
    
		largest = left
	}else{
    
    
		largest = i;
	}
	if (right < length && arr[largest] < arr[right]) {
    
    
		largest = right
	}
	//如果不是i是最大节点 以node作为辅助节点 交换位置
	if (largest != i) {
    
    
		arr[i] = arr[largest];
		arr[largest] = node;
		MaxHeap(arr,largest,length);
	}
}
//建立一个最大堆
function BuildMaxHeap(arr,len){
    
    
	if(len%2!=0){
    
    
		len = len +1 ;
	}
	for(let i = len/2;i>=0;i--){
    
    
		MaxHeap(arr,i,len)
	}
}

Guess you like

Origin blog.csdn.net/weixin_38616850/article/details/110877410