C Language Practice: Number Search - Binary Search
Revision as of 17:15, 13 March 2022 by Eric (talk | contribs) (Created page with "== Search for a Number - Binary Search == * Step 1: Define a number binary search function * Step 2: Get all the arguments needed in main <syntaxhighlight lang="c" line style="border: 1px dashed red;"> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int findnum(int totalnum, int numcheck, int numlist[totalnum]) { int i, place = totalnum / 2; for (i = 0; i <= totalnum; i++) { if (numlist[place] == numcheck) {...")
Search for a Number - Binary Search
- Step 1: Define a number binary search function
- Step 2: Get all the arguments needed in main
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int findnum(int totalnum, int numcheck, int numlist[totalnum])
{
int i, place = totalnum / 2;
for (i = 0; i <= totalnum; i++)
{
if (numlist[place] == numcheck)
{
printf("The number %d is found at position: %d\n", numcheck, place + 1);
return place + 1;
}
else if (numlist[place] < numcheck)
{
place = place + place / 2;
}
else
{
place = place / 2;
}
}
printf("Number not found.\n");
return 0;
}
int main(void)
{
int totalnum;
printf("How many numbers do you want to test: \n");
scanf("%d", &totalnum);
int numlist[totalnum];
printf("Please input %d numbers: \n", totalnum);
for (int i = 0; i < totalnum; i++)
{
scanf("%d", &numlist[i]);
}
int numcheck;
printf("What number are you looking for?: \n");
scanf("%d", &numcheck);
findnum(totalnum, numcheck, numlist);
return 0;
}