推排序:

将完全二叉树构造成堆

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 构造堆
{
    class Program
    {
        static void Main(string[] args)
        {
            //完全二叉树使用顺序存储的
            int[] array = new int[] { 34, 88, 56, 90, 85, 33, 24, 68, 94, 77, 57 };
            for (int i = array.Length/2; i >=1 ; i--)//对每个堆进行排序
            {
                int MaxIndex = i;
                int temp = i;
                while(true)
                {
                    int RightChild = temp * 2 + 1;
                    int LiftChild = temp* 2;
                    if(RightChild<=array.Length&&array[RightChild-1]>array[MaxIndex-1])//右节点大就把他放入父节点位置
                    {
                        MaxIndex = RightChild;
                    }
                    if(LiftChild<=array.Length&&array[LiftChild-1]>array[MaxIndex-1])//右节点大就把他放入父节点位置
                    {
                        MaxIndex = LiftChild;
                    }
                    if(MaxIndex!=temp)//如果节点调换位置,就把调换位置的节点在调节
                    {
                        int value = array[temp-1];
                        array[temp-1] = array[MaxIndex - 1];
                        array[MaxIndex - 1] = value;
                        temp = MaxIndex;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            foreach (var  item in  array)//将排序好的完全二叉树输出
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();

        }
    }
}

 

posted on 2019-08-09 11:49  晴耕--雨读  阅读(112)  评论(0编辑  收藏  举报