mirror of
https://github.com/RolandWH/ceesort.git
synced 2025-06-28 13:01:18 +01:00
initial commit
This commit is contained in:
32
src/bsrch.c
Normal file
32
src/bsrch.c
Normal file
@ -0,0 +1,32 @@
|
||||
#include "bsrch.h"
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdbool.h>
|
||||
#include <math.h>
|
||||
|
||||
|
||||
int bsrch(int target, int* arr, size_t n)
|
||||
{
|
||||
bool found = false;
|
||||
int start = 0, end = n - 1;
|
||||
if (arr[start] > target || arr[end] < target) return -1;
|
||||
int mid = round((start + end) / (double)2);
|
||||
|
||||
while (!found)
|
||||
{
|
||||
if (arr[mid] == target) found = true;
|
||||
if (start == end && !found) return -1;
|
||||
else if (arr[mid] < target)
|
||||
{
|
||||
start = mid + 1;
|
||||
mid = roundf((start + end) / (float)2);
|
||||
}
|
||||
else if (arr[mid] > target)
|
||||
{
|
||||
end = mid - 1;
|
||||
mid = roundf((start + end) / (float)2);
|
||||
}
|
||||
}
|
||||
|
||||
return mid;
|
||||
}
|
5
src/bsrch.h
Normal file
5
src/bsrch.h
Normal file
@ -0,0 +1,5 @@
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
|
||||
|
||||
int bsrch(int target, int* arr, size_t n);
|
30
src/ceesort.c
Normal file
30
src/ceesort.c
Normal file
@ -0,0 +1,30 @@
|
||||
#include "bsrch.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
int* arr = malloc((argc - 1) * sizeof(int));
|
||||
for (int i = 1; i < argc; i++)
|
||||
{
|
||||
arr[i - 1] = atoi(argv[i]);
|
||||
}
|
||||
|
||||
int target;
|
||||
printf("Enter number to search for: ");
|
||||
scanf("%d", &target);
|
||||
int result = bsrch(target, arr, argc - 1);
|
||||
|
||||
if (result != -1)
|
||||
{
|
||||
printf("Value found at index: %d\n", result);
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("Value not found\n");
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
Reference in New Issue
Block a user