C++堆(数据结构堆也就是树状结构)排序

#include<iostream>
using namespace std;


int arr[10] = { 2,8,3,9,1,4,6,7,0,5 };
void swap(int *a, int *b)
{
	int temp = *a;
	*a = *b;
	*b = temp;
}

void show(int *arr,int n)
{
	for (size_t i = 0; i < n; i++)
	{
		cout << arr[i] << " ";
	}
	cout << endl;

}


void heapsort(int *arr, int n)
{
	for (size_t i = n; i >0; i--)
	{
		for (size_t j = i-1; j > 0; j--)
		{
			int childen = j;
			int father = j / 2;

			if (j<i-1&&arr[j]<arr[j+1])
			{
				childen++;
			}

			if (arr[childen]>arr[father])
			{
				swap(arr[childen], arr[father]);
			}

		}

		swap(arr[0], arr[i - 1]);

	}


}
int main(int argc, char *argv[])
{
	heapsort(arr, 10);
	show(arr,10);

	system("pause");
	
}

猜你喜欢

转载自blog.csdn.net/haku_yyf/article/details/79517073