0

I would like to test if my binary search function is working correctly. I have created an array that is passed into a working bubble sort function. Printing the sorted array works just fine, all I want to do now is to print a success message then the needle is found in the haystack per the binary search.

#include <stdio.h>    
#include <cs50.h>

int main(void)
{
    int n = 5 ;
    int value = 2 ;
    int values[] = {3,4,1,5,2} ;
    bool iter ;
    // O(n^2) sorting algorithm
    do
    {
        iter = false ;
        for (int i = 0; i < n - 1 ; i++)
        {
            if (values[i] > values[i + 1])
            {
                int temp_val = values[i] ;
                values[i] = values[i + 1] ;
                values[i + 1] = temp_val ;
                iter = true ;
            }
        }
    } 
    while (iter) ;

    // prints the array to test if the function is working correctly
    for (int i = 0; i < n ; i++)
        {
            printf("%d, ", values[i]) ;
        } 
        printf("\n") ;


    // binary function using values declared above
    int ending = n - 1 ;
    int beggining = 0 ;

    while (ending >= beggining)
    {
        int middle = (beggining + ending) / 2 ;
        if (values[middle] == value)
        {
            return true ;
        // prints success message as soon as the needle has been found in haystacks
        printf("needle of value %d found!\n", values[middle]) ;
        }

        else if (values[middle] > value)
        {
            ending = middle - 1 ;
        }
        else
        {
            beggining = middle + 1 ;
        }
    }
    return false ;

    return 0 ;
}

1 Answer 1

0

If you want to test the function, you should create the search function and call it from main. Then, in main, print a message based on the return value received from the call to search().

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • All sorted thanks @Cliff B Commented Sep 13, 2016 at 17:53

You must log in to answer this question.

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