Пример #1
0
        public static List <T> Sort <T>(List <T> list) where T : IComparable <T>
        {
            // 1- re-arrange elements in the list into a max heap.
            var maxHeap = new MaxBinaryHeap <T, T>(ToHeapList(list));

            maxHeap.BuildHeap_Recursively(list.Count);

            // 2- Starting from last element in the list, repeat the following two steps for all the elements in the list, except the first one.
            for (int i = list.Count - 1; i > 0; i--)
            {
                /* Since the root element/node in a max heap is the maximum value in the list, putting it in the last position of the unsorted part of the array, determines its final position in an array that is eventually ordered ascending.*/
                Utils.Swap(maxHeap.HeapArray, 0, i);

                /* Since the new value in the root position of the heap (index :0) may not be in its correct position, heap-order-wise, then bubble it down, until it reaches its correct position.*/
                maxHeap.BubbleDown_Recursively(0, i);
            }

            return(ToList(maxHeap.HeapArray));
        }