Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _CRT_SECURE_NO_WARNINGS
- #include <cstdio>
- #include <cstdlib>
- int particleAmount;
- int *particleValue;
- int queryAmount;
- int *queryValue;
- int searchUntilLeftIndexFound(int *arr, int query, int size)
- {
- int result = 0;
- int p = size;
- int l = 0;
- int s;
- while (true)
- {
- s = (l + p) / 2;
- if (s == query)
- p = s - 1;
- else if (s < query)
- l = s + 1;
- if (l + 1 == p)
- {
- if (l == query)
- result = l;
- else
- result = p;
- break;
- }
- }
- return result;
- }
- int searchUntilRightIndexFound(int *arr, int query, int size, int _s)
- {
- int result = 0;
- int p = size;
- int l = _s;
- int s;
- while (true)
- {
- s = (l + p) / 2;
- if (s == query)
- l = s + 1;
- else if (s > query)
- p = s - 1;
- if (l + 1 == p)
- {
- if (p == query)
- result = p;
- else
- result = l;
- break;
- }
- }
- return result;
- }
- int binarySearch(int *arr, int query, int size)
- {
- int result = 0;
- int p = size;
- int l = 0;
- int s;
- while (true)
- {
- s = (p + l)/2;
- if (s > query)
- p = s - 1;
- else if (s < query)
- l = s + 1;
- else if (s == query)
- {
- int leftIndex = searchUntilLeftIndexFound(arr, query, size);
- int rightIndex = searchUntilRightIndexFound(arr, query, size, s);
- result = rightIndex - leftIndex + 1;
- break;
- }
- }
- return result;
- }
- int main()
- {
- // Get particle amount
- scanf("%d", &particleAmount);
- // Create array containing particle value
- particleValue = new int[particleAmount];
- // Get value of each particle TU WYPIERDALA NA SCANF
- for (int i = 0; i < particleAmount; i++)
- scanf("%d", particleValue[i]);
- // Get amount of queries
- scanf("%d", &queryAmount);
- // Create array containing query value
- queryValue = new int[queryAmount];
- // Get value of each query
- for (int i = 0; i < queryAmount; i++)
- scanf("%d", queryValue);
- // Print value of each query
- for (int i = 0; i < queryAmount; i++)
- printf("%d", binarySearch(particleValue, queryValue[i], particleAmount));
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement