Skip to main content
4 of 4
added 1185 characters in body

pset3's helpers.c gives segmentation fault error

Following is the code that I've written for helpers.c and it uses Selection sort and Binary Search

[code removed to comply to academic honesty]

/**
 * Sorts array of n values.
 */
void sort(int values[], int n)
{
    // TODO: implement an O(n^2) sorting algorithm i.e. Selection Sort
    int temp;
    for (int i = 0; i < n - 1; i++)
    {
        int min = values[i];
        
        for (int j = i + 1; j < n; i++)
        {
            if(values[j] < values[min])
            min = values[j];
        
            if (min != values[i])
            {
                temp = values[min];
                values[min] = values[i];
                values[i] = temp;
            }
        }
        
    }
    
}

I'm unable to figure out that why is it giving me segmentation fault error whenever I run it. What is causing this bug?

EDIT:

Code for Binary Search

bool search(int value, int values[], int n)
{
    // TODO: implement a searching algorithm i.e. Binary Search
    if (n == 1 && values[0] == value)
    {
        return true;
    }
    
    while (n > 1)
    {
        int middle = round(n / 2); 

        if (value == values[middle])
        {
            return true;
        }    
        else if (value < values[middle])
        {
            for(int p = middle - 1; p > 0; p--)
            {
                if (value == values[p])
                {
                    return true;
                }
            }
        }
        else if (value > values[middle])
        {
            for(int p = middle + 1; p <= n; p++)
            {
                if (value == values[p])
                {
                    return true;
                }
                                
            }
        }
        else
            return false;
        
    }
    return false;
}