Search code examples
ctimemergesort

why Mergesort wall time is always 0? can someone help me pls...?


I am trying to implement merge sort algorithm and somehow I always get total_wall=0? Can someone please help me? Is there somehow, I miss, because I already double check the result of the mergesort and the array is already sorted after the sorting and in the initialized state, the array is not yet unsorted?

Thank before for your help.

this is my code:

int sorting (void) {
    clock_t start_CPU, total_CPU;
    time_t start_Wall, end_Wall, total_Wall;

    start_CPU = clock ();
    start_Wall = time (NULL);

    sorting_partly(0, array_size - 1);

    end_Wall = time (NULL);
    total_CPU = clock () - start_CPU;
    total_Wall = difftime (end_Wall, start_Wall);

    printf ("total_cpu:\t %.3f \n", (float) total_CPU / CLOCKS_PER_SEC);
    printf ("total_wall:\t %.3f\n", (float) total_Wall);

    return 1;
}

int sorting_partly(int left, int right) {   
    int i = 0,accu = 0;
    int length = right - left + 1;
    int pivot  = (left + right) / 2;
    int merge1 = left, merge2 = pivot + 1;    
    int temp_array[length], temp_accu;

    if (left == right) {
        return 0;
    } else {
        sorting_partly (left, pivot); sorting_partly (pivot + 1, right);
    }

    for (accu = 0; accu <= pivot && accu + pivot + 1  <= right; accu++) {
        if (array_input[merge1] <= array_input[merge2]) {
            temp_array[accu] = array_input[merge1];
            merge1++;
        } else {
            temp_array[accu] = array_input[merge2];
            merge2++;
        }
    }

    for (temp_accu = merge1; temp_accu <= pivot; temp_accu++) {
        temp_array[accu] = array_input[temp_accu];
        accu++;
    }

    for (temp_accu = merge2; temp_accu <= right; temp_accu++) {
        temp_array[accu] = array_input[temp_accu];
        accu++;
    }

    for (i = 0; i < length; i++) {
        array_input[i + left] = temp_array[i];
    }

    return 1;
}

Solution

  • The problem is this line:

    total_Wall = difftime (end_Wall, start_Wall);
    

    total_Wall is of type time_t which is probably an integral type, whilst difftime returns a double. You are probably getting a warning that you are loosing precision. Try changing total_Wall to double or float and see what happens.