0

i had written the C code for sort and search it is not working yet my code for helper.c is

/**
 * helpers.c
 *
 * Helper functions for Problem Set 3.
 */

#include <cs50.h>

#include "helpers.h"

/**
 * Returns true if value is in array of n values, else false.
 */
bool search(int value, int values[], int n)
{
    // checking for the n (-ve or +ve )
    if (n < 0)
    {
        return false;
    }
    else
    {
        // searching algorithm
        int flag = 0;
        int position;
        int low = 0;
        int high = n - 1;
        int mid = (low + high) / 2;
        while (low < high)
        {
            if (values[mid] == value)
            {
                flag = 1;
                position = mid;
                break;
            }
            else
            {
                if (values[mid] > value)
                {
                    high = mid - 1;
                }
                else
                {
                    low = mid + 1;
                }
            }
            mid = (low + high) / 2;
        }
        return flag;
    }
}

/**
 * Sorts array of n values.
 */
void sort(int values[], int n)
{
    // O(n^2) sorting algorithm
    for (int x = 0; x < (n - 1); x++)
    {
        for (int y = (x + 1); y < n; y++)
        {
            if (values[x] > values[y])
            {
                int temp = values[x];
                values[x] = values[y];
                values[y] = temp;
            }
        }
    }

    return;
}
0

Use while (low <= high) instead of while (low < high)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .