-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathFindingOccurenceinSortedArrayUsingBS.cpp
122 lines (64 loc) · 1.44 KB
/
FindingOccurenceinSortedArrayUsingBS.cpp
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include<iostream>
using namespace std;
//program to find number of occurences of a a number in a sorted array using Binary search
//function to sort an array-QUICK SORT
//function to partiton the array into 2 parts
#define n 8
int Partition(int *arr,int start,int end) {
int Pivot = arr[end];
int Pindex = start;
for(int i =start;i<end ;i++)
{
if( arr[i] <= Pivot)
{
swap(arr[i],arr[Pindex]);
Pindex++;
}
}
swap(arr[Pindex],arr[end]);
return Pindex;
}
void QuickSort(int *arr,int start, int end)
{
if(start < end) {
int Pindex = Partition(arr,start,end);
QuickSort(arr,start,Pindex-1);
QuickSort(arr,Pindex+1 ,end);
}
}
//function to search for occurences in an array using Binary search
int BinarySearch(int *arr , int start, int end, int x )
{
int count= 0;
if(start <= end )
{
int mid = (start + (end-start)/2 );
//coounting the occurences of a number
for(int i=start;i<end;i++)
{
if(arr[i]==x)
{
count++;
}
}
if(x==arr[mid])
{
return count;
}
if(x > arr[mid]) {
return BinarySearch(arr,mid+1,end,x);
}
return BinarySearch(arr,start,mid-1,x);
}
}
int main () {
int arr[n]={10,12,15,10,10,1,4,10};
//sorting the array
QuickSort(arr,0,n-1);
for(int i=0;i<n;i++) {
cout<<arr[i]<<"\t";
}
cout<<endl;
cout<<BinarySearch(arr,0,n-1,10);
return 0;
}