Analysis topic: Arrays are sorted to find out the number of times a given number key appears,
Method 1, the most intuitive method is to iterate over the array, time complexity O (N)
Method 2, can be found with the help of two points, time complexity of O (LOGN)
Find out where key appears at the far left and find out where the rightmost key appears.
size_t getlow (int *array,int size, int k)
{
size_t left = 0;
size_t right = size-1;
while (left < right)
{
int mid = (left + right)/2;
if (Array[mid] >= k) Right
= mid;
else left
= mid + 1;
}
return left;
}
size_t getRight (int *array, int size, int k)
{
size_t left = 0;
size_t right = size-1;
while (left < right)
{
int mid = (left + right)/2;
if (Array[mid] <= k) Left
= mid;
else right
= mid-1;
}
return right;
}
int main ()
{
int arr[] = {0, 1, 1, 2, 2, 2, 2, 4, 4, 4};
int size = sizeof (arr)/sizeof (*ARR);
size_t left = Getlow (arr, size, 2);
size_t right = GetRight (arr, size, 2);
size_t count = right-left + 1;
return 0;
}
Recursive algorithm
Note: The parameter count is a reference.
void GetCount (int *array,int left,int right, int. k,int& count)
{
if (left > right)
return;
int mid = (left + right)/2;
if (array[mid] = = k)
{
++count;
GetCount (array, left, Mid-1, K, count);
GetCount (Array, mid + 1, right, K, count);
}
else if (Array[mid] > K)
getcount (array, left, Mid-1, K, count);
else
GetCount (array, mid + 1, right, K, count);
}
Two-point search
If the interval is open, right = Length,left < Right,right = Mid.
[] closed interval
int binsearch (int arr[],int length, int key)
{
int left = 0;
int right = Length-1;
int mid = 0;
while (left <= right)
{
mid = (left + right) >> 1;
if (Arr[mid] < key) Left
= mid + 1;
else if (Arr[mid] > key) Right
= mid-1;
else
return mid;
}
return-1;
}
* In an ordered array, find the first numeric upper_bound function greater than k *
int firstgreat (int *arr,int size,int k)
{
int left = 0, right = size-1;
while (left <= right)
{
int mid = (left + right)/2;
if (Arr[mid] <= k) Left
= mid + 1;
else right
= mid-1;
}
Return left < size? Left:-1;
}
in an ordered array, find the first number greater than or equal to K, the Lower_bound function
int firstgreatorequal (int *arr,int size,int k) {int left = 0, right = size-1;
while (left <= right) {int mid = (left + right)/2;
if (Arr[mid] < K) left = mid + 1;
else right = mid-1; } return left < size?
Left:-1; }