Data Structures - Sorting Algorithms, Selection Sort, Heap Sort

A heap is a complete binary tree with the following properties: the value of each node is greater than or equal to the value of the left and right child nodes, which is called a big top heap, or the value of each node is less than or equal to the value of the left and right child nodes , called the small top heap. Heapsort consists of the following steps:

1. Build an unordered sequence into a heap, and select a large-top heap or a small-top heap according to the requirements of ascending and descending order.

2. Swap the top element of the heap with the end element - "sink" the largest element to the end of the array

3. Readjust the structure so that it satisfies the definition of the heap, and then continue to swap the top and current end elements of the heap. until the entire sequence is in order.

//堆排序
/*******************************************************************/
//调整堆为大顶堆
void adjustHeap(int *a,int i, int size)    
{
	int lchild = 2 * i;   //左孩子
	int rchild = 2 * i + 1;   //右孩子

	int maxIndex = i;   //最大值的下标
	if (i<=size/2)
	{
		if (lchild <= size && a[lchild] > a[maxIndex])
		{
			maxIndex = lchild;
		}
		if (rchild <= size && a[rchild] > a[maxIndex])
		{
			maxIndex = rchild;
		}
		if (maxIndex != i)
		{
			int temp = a[maxIndex];
			a[maxIndex] = a[i];
			a[i] = temp;
			adjustHeap(a, maxIndex, size);   //i<=size/2是防止此处对叶子节点进行调整
		}
	}
}
//建立大顶堆
void buildHeap(int *a, int size)
{
	int parentNode = size / 2;    //最大非叶子节点
	for (int i=parentNode;i>=1;i--)
	{
		adjustHeap(a, i, size);
	}
}
//堆排序实现
void heapSort(int *a, int size)
{
	for (int i=size;i>1;i--)
	{
		buildHeap(a, i);
		int temp = a[i];
		a[i] = a[1];
		a[1] = temp;
	}
}

 

Guess you like

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