// To heapify a subtree rooted with node i which is // an index in arr[]. n is size of heap void heapify(MyFileArray arr, int n, int i) { int largest = i; // Initialize largest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && 1 == Comparer <IntFloat> .Default.Compare(arr[l], arr[largest])) { largest = l; OperationCount += 1; } // If right child is larger than largest so far if (r < n && 1 == Comparer <IntFloat> .Default.Compare(arr[r], arr[largest])) { largest = r; OperationCount += 1; } OperationCount += 4; // If largest is not root OperationCount += 1; if (largest != i) { IntFloat swapp = arr[i]; Swap(i, largest, arr); //arr[i] = arr[largest]; arr.WriteToFile(largest, swapp); //arr[largest] = swapp; OperationCount += 4; // Recursively heapify the affected sub-tree heapify(arr, n, largest); } }
public void sort(MyFileArray arr, int length) { int n = length; OperationCount += 1; // Build heap (rearrange array) for (int i = n / 2 - 1; i >= 0; i--) { heapify(arr, n, i); OperationCount += 2; } // One by one extract an element from heap for (int i = n - 1; i >= 0; i--) { // Move current root to end IntFloat temp = arr[0]; Swap(i, 0, arr); //arr[0] = arr[i]; arr.WriteToFile(i, temp); //arr[i] = temp; // call max heapify on the reduced heap heapify(arr, i, 0); OperationCount += 5; } }