简体   繁体   中英

C.Heapsort .Count the number of swaps and comparisons

The sorting seems to be working correctly. At least it sorts correctly:) It remains only to count the number of comparisons and swaps. How to calculate and output it?Somehow stalled at this point.. I will be very grateful for your help.If you demonstrate it with the updated code, I will be doubly grateful.

#include <stdio.h>
#include <stdlib.h>

void keyDown(int* arr, int n, int head)
{
    int j;
    if(2*head + 2 < n && arr[2*head + 1] < arr[2*head + 2])
    {
        j = 2*head + 2; 
    }
    else j = 2*head + 1;

    while(arr[head] < arr[j] && head < n / 2)
    {
        int tmp = arr[head];
        arr[head] = arr[j];
        arr[j] = tmp;
    
        head = j;

        if(2*head + 2 < n && arr[2*head + 1] < arr[2*head + 2])
        {
            j = 2*head + 2; 
        }
        else j = 2*head + 1;
    }

}
void heapSort(int* arr, int n)
{  
    int i;
    for(i = n/2 - 1; i >= 0; i--)
    {
        keyDown(arr,n,i);
    }
    int l = n;
    while(l > 1)
    {  
        l--;
        
        int tmp = arr[l];
        arr[l] = arr[0];
        arr[0] = tmp;
        
        keyDown(arr,l,0);
    }
}
int main(int argc, char *argv[]) {
    int n=10;
    int start, end,i;
    int *arr;
        arr=(int *)malloc(n*sizeof(int));
        time_t invocation_time = time(NULL);
        srand(invocation_time);
        int s;
        for (s=0;s<n;s++)
        {
            arr[s] = rand() % 50;
            printf ("%d \n", arr[s]);
        }
        printf ("\n");  
        heapSort(arr, n);
        for (i=0;i<n;i++){
            printf ("%d \n", arr[i]);   
        }
    return 0;
}

count the number of comparisons and swaps

make functions

//global counters
unsigned comparisons = 0, swaps = 0;

int lessthan(int a, int b) {
    comparisons++;
    return (a < b);
}
void swap(int *a, int *b) {
    swaps++;
    int tmp = *a; *a = *b; *b = tmp;
}

and then replace comparisons and swaps in your existing code with the specific function you need.

int main(int argc, char **argc) {
    //...
    if (lessthan(a[i], a[j])) swap(a+i, a+j);
    //...
    printf("comparisons: %u; swaps: %u\n", comparisons, swaps);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM