-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.c
More file actions
69 lines (57 loc) · 1.42 KB
/
binary_search.c
File metadata and controls
69 lines (57 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Given a sorted array of N integers representing the rollno of students in class and a target student rollno, determine if the target student exists in the class using the binary search algorithm. If student exists in the class, print the seat number of the student. Consider the seat number as the index of the sorted array.
// Input Format
// The first line reads the array of student register numbers
// The second line reads the search element
// Output Format
// Seat number of the student
// For example:
// Input Result
// 100 101 102 103 104 105 105 106 107 108
// 103
// 3
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int binarySearch(int arr[], int n, int x)
{
int first = 0, last = n - 1, mid;
while (first <= last)
{
mid = (first + last) / 2;
if (arr[mid] == x)
{
return mid;
}
else if (x > arr[mid])
{
first = mid + 1;
}
else
{
last = mid - 1;
}
}
return -1;
}
int main()
{
char arr[1000];
int arrr[100];
int x, k = 0, a, n = 0;
scanf("%[^\n]", arr);
scanf("%d", &x);
char *y = strtok(arr, " ");
while (y != NULL)
{
a = atoi(y);
arrr[n] = a;
n++;
k++;
y = strtok(NULL, " ");
}
if (binarySearch(arrr, n, x) != -1)
{
printf("%d", binarySearch(arrr, n, x));
}
return 0;
}