Skip to content

Instantly share code, notes, and snippets.

@LifeMoroz
Created October 18, 2013 22:50
Show Gist options
  • Save LifeMoroz/7049396 to your computer and use it in GitHub Desktop.
Save LifeMoroz/7049396 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <time.h>
int search(int *a, int n, int x)
{
size_t first = 0; /* Номер первого элемента в массиве */
size_t last = n; /* Номер элемента в массиве, СЛЕДУЮЩЕГО ЗА последним */
/* Если просматриваемый участок непустой, first<last */
size_t mid = first + (last - first) / 2;
if (n == 0)
{
return -1;
}
else if (a[0] > x)
{
return 0;
}
else if (a[n - 1] < x)
{
return n;
}
while (first < last)
{
if (x <= a[mid])
{
last = mid;
}
else
{
first = mid + 1;
}
mid = first + (last - first) / 2;
}
return last;
}
int main()
{
int n, m;
std::cin>> n >> m;
int *A = new int[n];
int B;
for(int i=0; i<n; i++)
{
std::cin>>A[i];
}
for(int i=0; i<m; i++)
{
std::cin>>B;
std::cout << search(A,n,B)<<std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment