-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_search.c
81 lines (69 loc) · 1.82 KB
/
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
// Lab Program-1
// Date-2-May-2023
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Bubble sort algo to sort the id generated by rand function before using binary search
void bubbleSort(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
// Swapping
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// binary search algorithm
int binarySearch(int arr[], int n, int key)
{
int low = 0, high = n - 1;
while (low <= high)
{
int mid = low + (high - low) / 2;
if (arr[mid] == key)
return mid;
else if (arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
return -1; // product is not found!
}
int main()
{
int n;
printf("Enter the total number of Products: ");
scanf("%d", &n);
int arr[n]; // statically creating array
srand(time(0)); // Seed the random number generator so that we always get random number of sequence on each execution
printf("product IDs are :\n");
for (int i = 0; i < n; i++)
{
arr[i] = rand() % 100000 + 1;
printf("%d ", arr[i]);
}
printf("\n");
bubbleSort(arr, n); // sorting the array elements
int key;
printf("Enter the product ID to be search: ");
scanf("%d", &key);
clock_t time;
double runtime;
time = clock();
int result = binarySearch(arr, n - 1, key);
time = clock() - time;
runtime = (double)time / CLOCKS_PER_SEC;
if (result != -1)
printf("Product is in stock.\n");
else
printf("Product is not in stock.\n");
printf("Time taken: %f seconds\n", runtime);
return 0;
}