1. 程式人生 > >堆排序演算法詳解及實現-----------c語言

堆排序演算法詳解及實現-----------c語言

堆排序原理:   堆排序指的是將大堆(小堆)堆頂(即下標為0)元素與堆的最後一個(即下標為hp->size - 1)元素交換,hp->size–,將其餘的元素再次調整成大堆(小堆),再次將堆頂(即下標為0)元素與堆的最後一個(即下標為hp->size - 1)元素交換,hp->size–,將其餘的元素再次調整成大堆(小堆)…………重複上述步驟,直至hp->size<1,將hp->size恢復為原來的值,迴圈不在繼續。 關於升序或者降序應該建立什麼堆??? 排升序:   若想排升序即最大值應該在最後面,根據堆排序原理,應該建大堆,這樣將堆頂元素與最後一個元素交換之後,最大值換到了最後面。 排降序:

  若想排降序即最小值應該在最後面,根據堆排序原理,應該建小堆,這樣將堆頂元素與最後一個元素交換之後,最小值換到了最後面。 堆的詳細概念以及建立等操作 **程式碼實現: **

#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>

typedef struct Heap
{
	int *data;
	int size;  
}Heap;
//堆排序
void Heap_Sort(int *array, int size);
//////////////////////////////////////////
void swap(int *x, int *y)
{
	int tmp = *x;
	*x = *y;
	*y = tmp;
}
void AdjustHeap(Heap *hp, int parent)
{
	int child = 2 * parent + 1;
	while (child < hp->size)
	{
		//找出左右孩子的較大值
		if (child + 1 < hp->size&&hp->data[child + 1] > hp->data[child])
		{
			child = child + 1;
		}
		//如果孩子中的最大值比父母大,則交換
		if (hp->data[child]>hp->data[parent])
		{
			swap(&hp->data[child], &hp->data[parent]);
			parent = child;
			child = 2 * parent + 1;
		}
		else
			return;
	}
}
//建立堆
void CreatHeap(Heap *hp, int *array, int size)
{
	int root = 0;
	hp->data = (int *)malloc(size*sizeof(int));
	if (hp->data == NULL)
	{
		return;
	}
	//先將陣列中的元素拷貝至堆中
	memcpy(hp->data, array, size*sizeof(int));
	//向下調整堆
	hp->size = size;

	root = (hp->size - 2) / 2;
	for (; root >= 0; root--)
	{
		AdjustHeap(hp, root);
	}
}
//排序
void HeapSort(Heap *hp)
{
	int size = hp->size;
	while (hp->size > 1)
	{
		swap(&hp->data[0], &hp->data[hp->size - 1]);
		hp->size--;
		AdjustHeap(hp, 0);
	}
	hp->size = size;
}
//堆排序
void Heap_Sort(int *array, int size)
{
	Heap hp;
	//建立堆
	CreatHeap(&hp, array, size);
	//排序
	HeapSort(&hp);
	memcpy(array,hp.data, size*sizeof(int));
}

測試檔案:

#include"sort.h"
void TestHeapSort()
{
	int array[] = { 10, 2, 5, 4, 6, 9, 3, 1, 0 };
	printf("排序前:");
	//列印
	Print(array, sizeof(array) / sizeof(array[0]));
	//堆排序
	Heap_Sort(array, sizeof(array) / sizeof(array[0]));
	printf("排序後:");
	//列印
	Print(array, sizeof(array) / sizeof(array[0]));
}
int main()
{
	TestHeapSort();
	system("pause");
	return 0;
}

在這裡插入圖片描述 時間複雜度: O(nlogn) 空間複雜度: O(1) 穩定性: 不穩定