Ejemplo n.º 1
0
        /// <summary>
        /// 构造最大堆
        /// </summary>
        /// <param name="A"></param>
        /// <param name="i"></param>
        public static void Max_Heapify(Heap A, int i)
        {
            var l       = Left(i);
            var r       = Right(i);
            var h       = A.size - 1;
            var largest = i;

            if (l <= h && A.A[l] > A.A[i])
            {
                largest = l;
            }
            else
            {
                largest = i;
            }

            if (r <= h && A.A[r] > A.A[largest])
            {
                largest = r;
            }
            if (largest != i)
            {
                var temp = A.A[i];
                A.A[i]       = A.A[largest];
                A.A[largest] = temp;
                Max_Heapify(A, largest);
            }
            Insertion_Sort.Print(A.A);
        }
Ejemplo n.º 2
0
        public static void Build_Max_Heap_s(Heap A)
        {
            A.size = 1;
            var max = (int)Math.Floor(A.size / 2M);

            Console.WriteLine($"length:{A.size}   max:{max}");
            for (var i = 2; i < A.A.Length; i++)
            {
                //Min_Heapify(A, i - 1);
                Max_Heap_Insert(ref A, i - 1);
            }
            Insertion_Sort.Print(A.A);
        }
Ejemplo n.º 3
0
        public static void Build_Max_Heap(Heap A)
        {
            A.size = A.A.Length;
            var max = (int)Math.Floor(A.size / 2M);

            Console.WriteLine($"length:{A.size}   max:{max}");
            for (var i = max; i > 0; i--)
            {
                //Min_Heapify(A, i - 1);
                Max_Heapify(A, i - 1);
            }
            Insertion_Sort.Print(A.A);
        }
Ejemplo n.º 4
0
 public static void Max_Heap_Insert(ref Heap A, int key)
 {
     A.size = A.size + 1;
     // Array.Resize(ref A.A, A.A.Length + 1);
     int[] temp = new int[A.A.Length + 1];
     Array.Copy(A.A, temp, A.A.Length);
     //把临时数组赋值给原数组,这时原数组已经扩容
     A.A = temp;
     //给扩容后原数组的最后一个位置赋值
     A.A[A.A.Length - 1] = int.MinValue;
     Insertion_Sort.Print(A.A);
     Console.WriteLine($"size{A.size}");
     Heap_Increase_Key(ref A, A.size - 1, key);
 }
Ejemplo n.º 5
0
 /// <summary>
 /// 排序
 /// </summary>
 /// <param name="A"></param>
 public static void HeapSort(Heap A)
 {
     Build_Max_Heap(A);
     for (int i = A.A.Length - 1; i >= 1; i--)
     {
         Console.WriteLine($"change: A[{i}]:{A.A[i]};A[0]:{ A.A[0]}");
         var temp = A.A[0];
         A.A[0] = A.A[i];
         A.A[i] = temp;
         A.size = A.size - 1;
         Max_Heapify(A, 0);
     }
     Insertion_Sort.Print(A.A);
 }