I meant to type in "binary search" not binary array whoops
hey, just wanted some help with this program. it's not my program, it was copied from a PowerPoint as notes for me to study off of, just putting the disclaimer here (it belongs to Pearson).
without further ado, here's the code:
Code:
#include <stdio.h>#define SIZE 15
size_t binarySearch(const int b[], int searchKey, size_t low, size_t high);
void printHeader(void);
void printRow(const int b[], size_t low, size_t mid, size_t high);
int main(void)
{
int a[ SIZE ];
size_t result;
int key;
size_t i;
for (i = 0; i < SIZE; ++i)
{
a[ i ] = (2 * i);
}
printf("%s", "Enter a number between 0 and 28:\n");
scanf("%d", &key);
result = binarySearch(a, key, 0, SIZE - 1);
if (result != -1)
{
printf("\n%d found in array element %d.\n", key, result);
}
else
{
printf("\n%d not found.\n", key);
}
}
size_t binarySearch(const int b[], int searchKey, size_t low, size_t high)
{
int middle;
while (low <= high)
{
middle = (low + high) / 2;
printRow(b, low, middle, high);
if (searchKey == b[ middle ])
{
return middle;
}
else if (searchKey < b[ middle ])
{
high = middle - 1;
}
else
{
low = middle + 1;
}
}
return -1;
}
void printHeader(void)
{
unsigned int i;
puts("\nSubscripts:\n");
for (i = 0; i < SIZE; ++i)
{
printf("%3u", i);
}
puts("");
for (i = 1; i <= 4 * SIZE; ++i)
{
printf("\n%s\n", "-");
}
puts("");
}
void printRow(const int b[], size_t low, size_t mid, size_t high)
{
size_t i;
for (i = 0; i < SIZE; ++i)
{
if (i < low || i > high)
{
printf("%s", " ");
}
else if (i == mid)
{
printf("%3d", b[ i ]);
}
else
{
printf("%3d", b[ i ]);
}
}
puts("");
}
What it should print (when you input 8, for example):
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
---------------------------------------
0 2 4 6 8 10 12 14 16 18 20 22 24
0 2 4 6* 8 10 12
8 10* 12
8*
8 found in array element 4.
(pretend that the numbers are aligned, the forum won't accept empty spaces)
Unfortunately, the hyphens and the 0-14 digits don't show up. The asterisks don't, either. According to the PowerPoint, it should work, yet it doesn't. Is it an issue with the compiler I have or the code itself? Thanks in advance!!!