added error checking and other tweaks

This commit is contained in:
Roland W-H 2022-03-26 13:30:43 +00:00
parent 5c89d7c8fb
commit 8091b93e68
2 changed files with 35 additions and 15 deletions

View File

@ -1,8 +1,7 @@
#include "bsrch.h" #include "bsrch.h"
#include <stddef.h>
#include <stdbool.h> #include <stdbool.h>
#include <math.h> #include <stddef.h>
int bsrch(int target, int* arr, size_t n) int bsrch(int target, int* arr, size_t n)
@ -10,7 +9,7 @@ int bsrch(int target, int* arr, size_t n)
bool found = false; bool found = false;
int start = 0, end = n - 1; int start = 0, end = n - 1;
if (arr[start] > target || arr[end] < target) return -1; if (arr[start] > target || arr[end] < target) return -1;
int mid = round((start + end) / (double)2); int mid = (start + end) / 2;
while (!found) while (!found)
{ {
@ -19,12 +18,12 @@ int bsrch(int target, int* arr, size_t n)
else if (arr[mid] < target) else if (arr[mid] < target)
{ {
start = mid + 1; start = mid + 1;
mid = roundf((start + end) / (float)2); mid = (start + end) / 2;
} }
else if (arr[mid] > target) else if (arr[mid] > target)
{ {
end = mid - 1; end = mid - 1;
mid = roundf((start + end) / (float)2); mid = (start + end) / 2;
} }
} }

View File

@ -1,30 +1,51 @@
#include "bsrch.h" #include "bsrch.h"
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
bool isint(char* s)
{
for (int i = 0; s[i]; i++)
{
if (s[i] == '-' && isdigit(s[i + 1])) continue;
if (!isdigit(s[i])) return false;
}
return true;
}
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
int* arr = malloc((argc - 1) * sizeof(int)); int* arr = malloc((argc - 1) * sizeof(int));
for (int i = 1; i < argc; i++) for (int i = 1; i < argc; i++)
{ {
if (!isint(argv[i]))
{
puts("Sorry but arguments must be integers");
return 1;
}
arr[i - 1] = atoi(argv[i]); arr[i - 1] = atoi(argv[i]);
} }
int target; char target_str[16];
printf("Enter number to search for: "); printf("Enter number to search for: ");
scanf("%d", &target); scanf("%s", target_str);
int result = bsrch(target, arr, argc - 1); while (!isint(target_str))
{
printf("Sorry but you must enter a whole number, try again: ");
scanf("%s", target_str);
}
int target = atoi(target_str);
if (result != -1) int result = bsrch(target, arr, argc - 1);
{ if (result == -1)
printf("Value found at index: %d\n", result); puts("Value not found");
}
else else
{ printf("Value found at index: %d\n", result);
printf("Value not found\n");
}
free(arr);
return 0; return 0;
} }