-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathfind_ceil_n_floor_in_array_logn.c
101 lines (97 loc) · 2.23 KB
/
find_ceil_n_floor_in_array_logn.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
* Date: 2018-11-10
*
* Description:
* Given a sorted array and an integer X, find floor and ceil of X from array.
* For example:
* A = [3, 4, 7, 8, 10], X = 5 so floor of 5 would be 4 and ceil would be 7
*
* Approach:
* First check for corner cases that is:
* - If X is smaller than first element in array
* - If X is larger than last element in array
* - If above 2 don't meet do a binary search and check if we are able to find
* same number as X in array or we are able to find a condition a[m] < X and
* a[m + 1] > X
*
* Complexity:
* O(logn)
*/
#include "stdio.h"
#include "stdlib.h"
int main() {
int i = 0;
int n = 0, x = 0;
int *a = NULL;
int floor = -1, ceil = -1;
int mid = 0, low = 0, high = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
a = (int *)malloc(sizeof(int)*n);
for (i = 0; i < n; i++) {
printf("Enter element[%d]: ", i);
scanf("%d",&a[i]);
}
printf("Enter element: ");
scanf("%d", &x);
if (x < a[0]) {
printf("Ceil - %d, Floor - Not possible\n", a[0]);
return 0;
}
else if (x > a[n - 1]) {
printf("Ceil - Not possible, Floor - %d\n", a[n - 1]);
return 0;
}
low = 0;
high = n - 1;
while (low < high) {
mid = (low + high)/2;
if (x == a[mid]) {
printf("Ceil - %d, Floor - %d\n", a[mid], a[mid]);
break;
}
else if ((a[mid] < x) && (a[mid + 1] > x)) {
printf("Ceil - %d, Floor - %d\n", a[mid + 1], a[mid]);
break;
}
else if (x > a[mid])
low = mid;
else
high = mid;
}
return 0;
}
/*
* Output:
* ------------------
* Enter number of elements: 4
* Enter element[0]: 1
* Enter element[1]: 2
* Enter element[2]: 3
* Enter element[3]: 4
* Enter element: 2
* Ceil - 2, Floor - 2
*
* Enter number of elements: 5
* Enter element[0]: 2
* Enter element[1]: 7
* Enter element[2]: 10
* Enter element[3]: 16
* Enter element[4]: 111
* Enter element: 50
* Ceil - 111, Floor - 16
*
* Enter number of elements: 3
* Enter element[0]: 4
* Enter element[1]: 5
* Enter element[2]: 6
* Enter element: 10
* Ceil - Not possible, Floor - 6
*
* Enter number of elements: 3
* Enter element[0]: 4
* Enter element[1]: 5
* Enter element[2]: 6
* Enter element: 1
* Ceil - 4, Floor - Not possible
*/