I would like to find the number of elements greater than a given number in an array. Like if I have the following array: { 10, 113, 34, 2, 19, 57} And want to look for numbers greater than 30 then I would get 3.
Here is my code
#include <stdio.h>
int main()
{
int array[] = { 10, 113, 34, 2, 19, 57};
int n = sizeof(array) / sizeof(array[0]);
int A = 30;
int l = 0;
int r = n - 1;
int leftGreater = n;
while (l <= r) {
int m = l + (r - l) / 2;
if (array[m] > A) {
leftGreater = m;
r = m - 1;
}
else
l = m + 1;
}
printf("%d",n - leftGreater);
}
But instead of 3, I'm getting 5. Can anyone please help me solve this?
A simple for
loop is enough:
#include <stdio.h>
int main(void)
{
int array[] = { 10, 113, 34, 2, 19, 57 };
int n = sizeof(array) / sizeof(array[0]);
int x = 30, res = 0;
for (int i = 0; i < n; i++)
{
if (array[i] > x)
{
res++;
}
}
printf("%d\n", res);
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.