Confusingly with two different heap implementations

Function 1

void min_heapify(int arr[],int n, int i){
    int j, temp;
    temp = arr[i];
    j = 2 * i;

    while (j <= n)
    {
        if (j < n && arr[j+1] < arr[j])
            j = j + 1;
        if (temp < arr[j])
            break;
        else if (temp >= arr[j])
        {
            arr[j/2] = arr[j];
            j = 2 * j;
        }
    }

    arr[j/2] = temp;
}

Function 2

void max_heapify(int 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 && arr[l] < arr[largest])
        largest = l;

    // If right child is larger than largest so far
    if (r < n && arr[r] < arr[largest])
        largest = r;

    // If largest is not root
    if (largest != i)
    {
        swap(arr[i], arr[largest]);

        // Recursively heapify the affected sub-tree
        heapify(arr, n, largest);
    }
}

Problem Details

Here heapification works the same way as make min_heap, but the problem is that I used the heap in this task below to solve it, but, unfortunately, function 2, which I implemented while watching the MIT lecture, did not help to solve this problem after watching for some time on the net I found the 1st function that worked without problems on this problem. I'm just confused, isn't that the same function? ------

Problem

Yes!! The name of the problem reflects your task; just add a set of numbers. But you can feel condescending, write a C / C ++ program to add a set of numbers. Such a problem will simply question your erudition. So, let's add some taste of ingenuity to it.

, - , . , 1 10, 11. 1, 2 3. :

1 + 2 = 3, cost = 3
1 + 3 = 4, cost = 4
2 + 3 = 5, cost = 5
3 + 3 = 6, cost = 6
2 + 4 = 6, cost = 6
1 + 5 = 6, cost = 6
Total = 9
Total = 10
Total = 11

, , , .

, N (2 ≤ N ≤ 5000), N ( 100000). , N . .

.

SampleInput

3    
1 2 3    
4    
1 2 3 4    
0    

SampleOutput

9
19
+4
2

, , , if, , if (left <= n) (left < n), . .

void min_heapify(int arr[],int n, int i){    
    int lowest = i; // Initialize lowest as root
    int left = 2*i ;
    int right = 2*i + 1;



 // If child is lower than root
    if(left <= n && arr[left] < arr[lowest]){
        lowest = left;
    }

    // If right child is lower than lowest
    if(right <= n && arr[right] < arr[lowest]){
        lowest = right;
    }
    // If lowest is not root
    if(lowest != i){ // also break condition
        swap(arr[i], arr[lowest]);

        //Recursively heapify
        min_heapify(arr, n, lowest);

    }
0

2 swap.

C - ,

swap(arr[i], arr[largest]);

.

:

swap(int *v1, int *v2) {
    int tmp = *v1;
    *v1 = *v2;
    *v2 = tmp;
}

:

swap(&arr[i], &arr[largest]);
0

All Articles