forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
01_Linear_Binary_Search.c
66 lines (61 loc) · 1.46 KB
/
01_Linear_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
#include <stdio.h>
int linearSearch(int arr[], int size, int element)
{
/*
Best Time Complexity : O(1)
Average Time Complexity : O(n)
Worst Time Complexity : O(n)
Worst Space Complexity : O(1)
*/
for (int i = 0; i < size; i++)
{
if (arr[i] == element)
{
return i;
}
}
return -1;
}
int binarySearch(int arr[], int size, int element)
{
/*
Best Time Complexity : O(1)
Average Time Complexity : O(logn)
Worst Time Complexity : O(logn)
Worst Space Complexity : O(1)
*/
int low, mid, high;
low = 0;
high = size - 1;
// 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;
}
}
return -1;
}
int main()
{
// Unsorted array for linear search
// int arr[] = {1,3,5,56,4,3,23,5,4,54634,56,34};
// int size = sizeof(arr)/sizeof(int);
// Sorted array for binary search
int arr[] = {1, 3, 5, 56, 64, 73, 123, 225, 444};
int size = sizeof(arr) / sizeof(int);
int element = 444;
int searchIndex = binarySearch(arr, size, element);
printf("The element %d was found at index %d \n", element, searchIndex);
return 0;
}