Ejemplo n.º 1
0
        private void maxHeapify(Heap heap, int i)
        {
            int leftIndex = heap.GetLeftIndex(i);
            int rightIndex = heap.GetRightIndex(i);

            int indexOfLargestItem = -1;
            if (leftIndex < heap.HeapSize && heap[leftIndex] > heap[i])
            {
                indexOfLargestItem = leftIndex;
            }
            else
            {
                indexOfLargestItem = i;
            }

            if (rightIndex < heap.HeapSize && heap[rightIndex] > heap[indexOfLargestItem])
            {
                indexOfLargestItem = rightIndex;
            }

            if (indexOfLargestItem != i)
            {
                heap.Swap(i, indexOfLargestItem);
                maxHeapify(heap, indexOfLargestItem);
            }
        }
Ejemplo n.º 2
0
        public int[] Sort(int[] items)
        {
            Heap heap = new Heap(items);
            buildMaxHeap(heap);

            for (int i = heap.Length - 1; i > 0; i--)
            {
                heap.Swap(0, i);
                heap.HeapSize--;
                maxHeapify(heap, 0);
            }

            return heap.AsArray();
        }