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 ;
}