-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcounting occurences of an element in O(logn).c
More file actions
81 lines (59 loc) · 1.54 KB
/
Copy pathcounting occurences of an element in O(logn).c
File metadata and controls
81 lines (59 loc) · 1.54 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
70
71
72
73
74
75
76
77
78
79
80
81
#include<stdio.h>
//find the first and last index
int first_occurence(int *arr, int l, int h, int x)
{
if(l<=h)
{
int mid=(l+h)/2;
if(x<arr[mid])
return first_occurence(arr,l,mid-1,x);
else if(x>arr[mid])
return first_occurence(arr,mid+1,h,x);
else if(x==arr[mid] && (x>arr[mid-1] || mid==l))
return 1;
else
return 0;
}
return -1;
}
int last_occurence(int *arr, int l, int h, int x)
{
if(l<=h)
{
int mid=(l+h)/2;
if(x<arr[mid])
return last_occurence(arr,l,mid-1,x);
else if(x>arr[mid])
return last_occurence(arr,mid+1,h,x);
else if(x==arr[mid] && (x<arr[mid+1] || mid==h))
return 1;
else
return 0;
}
return -1;
}
int count(int *arr, int n, int x)
{
if(last_occurence(arr,0,n-1,x)!=-1 && first_occurence(arr,0,n-1,x)!=-1)
return last_occurence(arr,0,n-1,x) - first_occurence(arr,0,n-1,x) + 1 ;
else
return 0;
}
int main()
{
int n,x,i;
printf("Enter the size of the array: ");
scanf("%d",&n);
int arr[n];
printf("\nEnter the array elements:\n\n");
for(i=0;i<n;i++)
{
printf("Enter the value: ");
scanf("%d",&arr[i]);
}
printf("\n\nEnter the element to be searched: ");
scanf("%d",&x);
printf("\nNo. of occurrences of %d: %d",x,count(arr,n,x));
printf("\n\n");
return 0;
}