Feras Wilson
Feras Wilson

Reputation: 390

Determine Big-O of heap creation function

What is the Big-O notation of this heapify method? I was expecting O(log n) but it does not add up? How do I make it O(log n)?

Assuming we have this:

int arr[] = {1, 3, 5, 2, 7, 9, 4, 6};
int n = arr.length;
int i = 0; // Start position



void heapify(int arr[], int n, int i) {
        int largest = i;
        int left = 2 * i + 1;
        int right = 2 * i + 2;

        if(left < n && arr[left] > arr[largest]) {
            largest = left;
        }

        if(right < n && arr[right] > arr[largest]) {
            largest = right;
        }

        if(largest != i) {
            int swap = arr[i];
            arr[i] = arr[largest];
            arr[largest] = swap;

            heapify(arr, n, largest);
        }
    }

Thanks,

Upvotes: 0

Views: 70

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198471

This is already O(log n). The value of i at least doubles with every recursive call, and when i >= n it stops, and after the first call i is at least one, so there can be at most O(log n) recursive calls.

Upvotes: 1

Related Questions