Search code examples
arrayscsortingswap

Unexpected behaviour when swapping elements in C list


Homework from uni, tl;dr is that we had to create functions: swap(args), sort(args), max(args) where sorting is in descending order.

Function that is the core of the problem is swap. Array arr is of type type double, so when I want to swap 2 elements in that list, I should use double type, however it produces output: 9.0 1.0 5.1 3.0 2.0 but when I change double buffer; to int buffer;, output changes and becomes correct sorted list of9.0 5.0 3.0 2.0 1.0 and the value 5.1 is rounded down to 5 because of the implicit conversion.

So the question is why?

Using VS Code with extensions C/C++, C/C++ Extension Pack, Code Runner Not sure of the compiler but it's latest version of mingw-something.

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

int max(double t[], int N, int p, int k){
   
    if(p == k){
        return t[p];
    }
    double max;
    int index;
    
    for(int i = p; i <= k; i++){
        if(t[i] > max){
            
            max = t[i];
            index = i;
        }
    }
    return index;
}

void swap(double t[], int N, int p, int k){
    double buffer;
    if(p >= 0 && k <= N-1){
        buffer = t[p];
        t[p] = t[k];
        t[k] = buffer;
    }
}

void sort(double t[], int N){
   
    int indexMax;
    int a = 0;
    int b = N - 1;
    
    do{
        indexMax = max(t, N, a, b);
        swap(t, N, indexMax, a);
        a++;
    }while(a < b);
}

int main()
{         
    printf("\noutput:\n\n");
    double arr[5] = {1, 5.1, 3, 9, 2};
    
    for(int i = 0; i < 5; i++){
        printf("%.1lf ", arr[i]);
    }printf("\n");
    
    sort(arr, 5);
    
    for(int i = 0; i < 5; i++){
        printf("%.1lf ", arr[i]);
    }
    printf("\n\nkurwa");
    
    return 0;
}

Solution

  • There are problems in the max function:

    1. When p == k it returns an element value (of type double) instead of an index.
    2. max has an uninitialized value in the comparisons until some element happens to be greater than the uninitialized value.
    3. If no element value is greater than the uninitialized max value, index will remain uninitialized and the function will return an uninitialized value.

    Here is an improved version of the max function:

    int max(double t[], int N, int p, int k){
       
        if(p >= k){
            return k;
        }
        double max = t[p];
        int index = p;
        
        for(int i = p + 1; i <= k; i++){
            if(t[i] > max){
                max = t[i];
                index = i;
            }
        }
        return index;
    }
    

    It initializes max and index to correspond to element p and then checks elements p+1 to k to find the element with the greatest value.

    The swap function is OK, but the sanity checks on the index values are not exhaustive. Here is a better sanity check:

        if(p >= 0 && p <= N-1 && k >= 0 && k <= N-1){