-
Notifications
You must be signed in to change notification settings - Fork 1
/
Linear_Vs_Binary_Search.c
82 lines (52 loc) · 1.29 KB
/
Linear_Vs_Binary_Search.c
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
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <stdio.h>
// Linear search
int Linersearch(int arr[], int size, int element){
for (int i = 0; i < size; i++)
{
if (arr[i]==element)
{
return i;
}
return -1;
}
}
// Binary search
int Binarysearch(int arr[], int size, int element){
int low,mid,high;
low = 0;
high = size-1;
// start searching
// Keep searching until low<=high
while (low<=high)
{
mid = (low+high)/2;
if (arr[mid]==element)
{
return mid;
}
if (arr[mid]<element)
{
low = mid + 1;
}
else{
high = mid - 1;
}
}
// searching ending
return -1;
}
int main()
{
// Unsorted array for linear search
// int arr[] = {1,23,45,5,56,677,889,9,121};
// int size = sizeof(arr)/sizeof(int);
// int element = 67;
// Sorted array for Binary search
int arr[] = {1,23,45,55,56,67,88,91,121};
int size = sizeof(arr)/sizeof(int);
int element = 121;
// int sb = Linersearch(arr,size,element);
int sb = Binarysearch(arr,size,element);
printf("The element %d is found at index: %d\n",element,sb);
return 0;
}