I am trying to write an iterative search in a C program.
The pseudo-code would look like this for it:
while length of list > 0
look at middle of list
if number found, return true
else if number is too high, only consider
left half of list
else if number is too low, only consider
right half of list
return false
I have already implemented a bubble sort (which I assume works). Here is my code right now. The search is currently linear. I need to somehow change it to a binary search (I would prefer to do it iteratively instead of recursively). I'm completely lost on how I should go about doing this though. Can someone please help me?:
#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include "helpers.h"
/*
* Returns true if value is in array of n values, else false.
*/
bool
search(int value, int array[], int n)
{
// TODO: re-implement as binary search
int min = 0;
int max = n;
int i;
i=(min+max)/2;
if(array[i] == value)
{
return true;
}
else if(min>=max)
{
return 1;
}
else if(array[i] > value)
{
max = i-1;
}
else if(array[i] < value)
{
min = i+1;
}
return false;
}
/*
* Sorts array of n values.
*/
void
sort(int values[], int n)
{
//set smade to false to start
//declares the_end as n-1
bool smade = false;
int the_end = n-1;
// TODO: implement an O(n^2) sort
while(the_end > 0)
{
for(int i = 0; i < the_end; i++)
{
int temp;
if (values[i] > values[i+1])
{
temp = values[i];
values[i] = values[i+1];
values[i+1] = temp;
smade=true;
}
}
if(! smade)
{
break;
}
the_end--;
}
return;
}