Search code examples
crecursionsegmentation-faultselection-sort

Same program is giving me different outputs


I'm trying to make a recursive version of selection sort. It's not completed yet. I've only managed to find the minimum element's index. When I run my program sometimes it works fine and outputs the correct value, but other times it gives me "1869833334" followed by a segmentation fault for some reason and I can't figure out why.

#include <stdio.h>

int MaxInd(int arr[], int i, int len, int max, int index){
    if (arr[i]>max){
        max=arr[i];
        index=i;
    }

    if(i==len-1){
        return index;
    }

    index = MaxInd(arr,i+1,len,max,index);
    printf("%d\n", index);
    return index;
}

int SelectionSort(int arr[], int len){
int index,max,i;
int k = MaxInd(arr, i, len, max, index);
}

int main(void){
    int arr[6] = {1,4,5,0,9,2};
    int len=sizeof(arr)/sizeof(arr[0]);
    int var=SelectionSort(arr, len);
    printf("final index is: %d\n",var);
}

Solution

  • int SelectionSort(int arr[], int len){
        int index,max,i;
        int k = MaxInd(arr, i, len, max, index);
    }
    

    index, max and i are uninitialzed, the results you get from this are different every time, because it is undefined behvaiour.

    Also

    int MaxInd(int arr[], int i, int len, int max, int index){
        if (arr[i]>max){
            max=arr[i];
            index=i;
        }
        ...
    

    You should check that i < len before you attempt to access arr[i], otherwise you could access beyond the limits of arr. You should put the check before accessing the value:

    int MaxInd(int arr[], int i, int len, int max, int index){
        if(i==len-1){
            return index;
        }
    
        if (arr[i]>max){
            max=arr[i];
            index=i;
        }
    
        ...