Count of smaller or equal elements in sorted array

22 Jun, 2022
Given a sorted array of size n. Find a number of elements that are less than or equal to a given element.Examples:  
Input : arr[] = {1, 2, 4, 5, 8, 10}
        key = 9
Output : 5
Elements less than or equal to 9 are 1, 2, 
4, 5, 8 therefore result will be 5.

Input : arr[] = {1, 2, 2, 2, 5, 7, 9}
        key = 2
Output : 4
Elements less than or equal to 2 are 1, 2, 
2, 2 therefore result will be 4. 
Naive approach: Search whole array linearly and count elements that are less than or equal to the key. 
Time Complexity: O(n).Auxiliary Space: O(1).Efficient approach: As the whole array is sorted we can use binary search to find result. Case 1: When key is present in array, the last position of key is the result.Case 2: When key is not present in array, we ignore left half if key is greater than mid. If key is smaller than mid, we ignore right half. We always end up with a case where key is present before middle element.  
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count smaller or equal// elements in sorted array.#include <bits/stdc++.h>using namespace std; // A binary search function. It returns// number of elements less than of equal// to given keyint binarySearchCount(int arr[], int n, int key){    int left = 0, right = n;     int mid;    while (left < right) {        mid = (right + left) >> 1;         // Check if key is present in array        if (arr[mid] == key) {                       // If duplicates are present it returns            // the position of last element            while (mid + 1 < n && arr[mid + 1] == key)                mid++;            break;        }         // If key is smaller, ignore right half        else if (arr[mid] > key)            right = mid;         // If key is greater, ignore left half        else            left = mid + 1;    }     // If key is not found    // in array then it will be    // before mid    while (mid > -1 && arr[mid] > key)        mid--;     // Return mid + 1 because of 0-based indexing    // of array    return mid + 1;} // Driver program to test binarySearchCount()int main(){    int arr[] = { 1, 2, 4, 5, 8, 10 };    int key = 11;    int n = sizeof(arr) / sizeof(arr[0]);    cout << binarySearchCount(arr, n, key);    return 0;}
// Java program to count smaller or equal// elements in sorted array. class GFG {   // A binary search function. It returns  // number of elements less than of equal  // to given key  static int binarySearchCount(int arr[], int n, int key)  {    int left = 0, right = n;     int mid = 0;    while (left < right) {      mid = (right + left) >> 1;       // Check if key is present in array      if (arr[mid] == key) {         // If duplicates are present it returns        // the position of last element        while (mid + 1 < n && arr[mid + 1] == key)          mid++;        break;      }       // If key is smaller, ignore right half      else if (arr[mid] > key)        right = mid;       // If key is greater, ignore left half      else        left = mid + 1;    }     // If key is not found in array then it will be    // before mid    while (mid > -1 && arr[mid] > key)      mid--;     // Return mid + 1 because of 0-based indexing    // of array    return mid + 1;  }   // Driver code  public static void main(String[] args)  {    int arr[] = { 1, 2, 4, 5, 8, 10 };    int key = 11;    int n = arr.length;    System.out.print(binarySearchCount(arr, n, key));  }} // This code is contributed by Anant Agarwal.
# Python program to# count smaller or equal# elements in sorted array. # A binary search function.# It returns# number of elements# less than of equal# to given keydef binarySearchCount(arr, n, key):     left = 0    right = n      mid = 0    while (left < right):             mid = (right + left)//2          # Check if key is present in array        if (arr[mid] == key):                     # If duplicates are            # present it returns            # the position of last element            while (mid + 1<n and arr[mid + 1] == key):                 mid+= 1            break                   # If key is smaller,        # ignore right half        elif (arr[mid] > key):            right = mid          # If key is greater,        # ignore left half        else:            left = mid + 1           # If key is not found in    # array then it will be    # before mid    while (mid > -1 and  arr[mid] > key):        mid-= 1      # Return mid + 1 because    # of 0-based indexing    # of array    return mid + 1 # Driver code arr = [1, 2, 4, 5, 8, 10]key = 11n = len(arr) print(binarySearchCount(arr, n, key)) # This code is contributed# by Anant Agarwal.
// C# program to count smaller or// equal elements in sorted array.using System; class GFG {     // A binary search function.    // It returns number of elements    // less than of equal to given key    static int binarySearchCount(int[] arr,                                 int n, int key)    {        int left = 0;        int right = n;         int mid = 0;        while (left < right) {            mid = (right + left) / 2;             // Check if key is            // present in array            if (arr[mid] == key) {                 // If duplicates are present                // it returns the position                // of last element                while (mid + 1 < n && arr[mid + 1] == key)                    mid++;                break;            }             // If key is smaller,            // ignore right half            else if (arr[mid] > key)                right = mid;             // If key is greater,            // ignore left half            else                left = mid + 1;        }         // If key is not found in array        // then it will be before mid        while (mid > -1 && arr[mid] > key)            mid--;         // Return mid + 1 because of        // 0-based indexing of array        return mid + 1;    }     // Driver code    static public void Main()    {        int[] arr = { 1, 2, 4, 5, 8, 10 };        int key = 11;        int n = arr.Length;        Console.Write(binarySearchCount(arr, n, key));    }} // This code is contributed by ajit.
<?php// PHP program to count// smaller or equal// elements in sorted array. // A binary search function.// It returns number of// elements less than of// equal to given keyfunction binarySearchCount($arr, $n, $key){    $left = 0;    $right = $n;    $mid;    while ($left < $right)    {        $mid = ($right + $left) / 2;         // Check if key is        // present in array        if ($arr[$mid] == $key)        {            // If duplicates are            // present it returns            // the position of            // last element            while ($mid + 1 < $n && $arr[$mid + 1] == $key)                $mid++;            break;        }         // If key is smaller,        // ignore right half        else if ($mid > -1 && $arr[$mid] > $key)            $right = $mid;         // If key is greater,        // ignore left half        else            $left = $mid + 1;    }     // If key is not found in    // array then it will be    // before mid    while ($arr[$mid] > $key)        $mid--;     // Return mid + 1 because    // of 0-based indexing    // of array    return $mid + 1;} // Driver Code$arr = array (1, 2, 4,              5, 8, 10);$key = 11;$n = sizeof($arr) ;echo binarySearchCount($arr, $n, $key); // This code is contributed by ajit?>
<script>     // Javascript program to    // count smaller or equal    // elements in sorted array.         // A binary search function. It returns    // number of elements less than of equal    // to given key    function binarySearchCount(arr, n, key)    {        let left = 0, right = n;         let mid;        while (left < right) {            mid = (right + left) >> 1;             // Check if key is present in array            if (arr[mid] == key) {                 // If duplicates are                // present it returns                // the position of last element                while ((mid + 1) < n &&                       arr[mid + 1] == key)                    mid++;                break;            }             // If key is smaller, ignore right half            else if (arr[mid] > key)                right = mid;             // If key is greater, ignore left half            else                left = mid + 1;        }         // If key is not found        // in array then it will be        // before mid        while (mid > -1 && arr[mid] > key)            mid--;         // Return mid + 1 because of 0-based indexing        // of array        return mid + 1;    }         let arr = [ 1, 2, 4, 5, 8, 10 ];    let key = 11;    let n = arr.length;    document.write(binarySearchCount(arr, n, key)); </script>
6
Time Complexity: O(n).Auxiliary Space: O(1).
Although this solution performs better on average, the worst-case time complexity of this solution is still O(n).The above program can be implemented using a more simplified binary search. The idea is to check if the middle element is greater than the given element then update right index as mid – 1 but if the middle element is less than or equal to key update answer as mid + 1 and left index as mid + 1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to count smaller or equal// elements in sorted array#include <bits/stdc++.h>using namespace std; // A binary search function to return// the number of elements less than// or equal to the given keyint binarySearchCount(int arr[], int n, int key){    int left = 0;    int right = n - 1;     int count = 0;     while (left <= right) {        int mid = (right + left) / 2;         // Check if middle element is        // less than or equal to key        if (arr[mid] <= key) {             // At least (mid + 1) elements are there            // whose values are less than            // or equal to key            count = mid + 1;            left = mid + 1;        }         // If key is smaller, ignore right half        else            right = mid - 1;    }     return count;} // Driver codeint main(){    int arr[] = { 1, 2, 4, 11, 11, 16 };    int key = 11;    int n = sizeof(arr) / sizeof(arr[0]);     cout << binarySearchCount(arr, n, key);     return 0;}
// Java program to count smaller or equalimport java.io.*; class GFG{     // A binary search function to return// the number of elements less than// or equal to the given keystatic int binarySearchCount(int arr[],                             int n, int key){    int left = 0;    int right = n - 1;     int count = 0;     while (left <= right)    {        int mid = (right + left) / 2;         // Check if middle element is        // less than or equal to key        if (arr[mid] <= key)        {             // At least (mid + 1) elements are there            // whose values are less than            // or equal to key            count = mid + 1;            left = mid + 1;        }         // If key is smaller, ignore right half        else            right = mid - 1;    }    return count;} // Driver codepublic static void main (String[] args){    int arr[] = { 1, 2, 4, 11, 11, 16 };    int key = 11;    int n = arr.length;     System.out.println (binarySearchCount(arr, n, key));}} // The code is contributed by Sachin.
# Python3 program to count smaller or equal# elements in sorted array # A binary search function to return# the number of elements less than# or equal to the given keydef binarySearchCount(arr, n, key):     left = 0    right = n - 1     count = 0     while (left <= right):        mid = int((right + left) / 2)         # Check if middle element is        # less than or equal to key        if (arr[mid] <= key):             # At least (mid + 1) elements are there            # whose values are less than            # or equal to key            count = mid + 1            left = mid + 1                 # If key is smaller, ignore right half        else:            right = mid - 1         return count # Driver codearr = [ 1, 2, 4, 11, 11, 16 ]key = 11n = len(arr) print( binarySearchCount(arr, n, key)) # This code is contributed by Arnab Kundu
// C# program to count smaller or equalusing System;     class GFG{     // A binary search function to return// the number of elements less than// or equal to the given keystatic int binarySearchCount(int []arr,                             int n, int key){    int left = 0;    int right = n - 1;     int count = 0;     while (left <= right)    {        int mid = (right + left) / 2;         // Check if middle element is        // less than or equal to key        if (arr[mid] <= key)        {             // At least (mid + 1) elements are there            // whose values are less than            // or equal to key            count = mid + 1;            left = mid + 1;        }         // If key is smaller,        // ignore right half        else            right = mid - 1;    }    return count;} // Driver codepublic static void Main (String[] args){    int []arr = { 1, 2, 4, 11, 11, 16 };    int key = 11;    int n = arr.Length;     Console.WriteLine(binarySearchCount(arr, n, key));}} // This code is contributed by PrinciRaj1992
<script>    // Javascript program to count smaller or equal    // elements in sorted array         // A binary search function to return    // the number of elements less than    // or equal to the given key    function binarySearchCount(arr, n, key)    {        let left = 0;        let right = n - 1;         let count = 0;         while (left <= right) {            let mid = parseInt((right + left) / 2, 10);             // Check if middle element is            // less than or equal to key            if (arr[mid] <= key) {                 // At least (mid + 1) elements are there                // whose values are less than                // or equal to key                count = mid + 1;                left = mid + 1;            }             // If key is smaller, ignore right half            else                right = mid - 1;        }         return count;    }         let arr = [ 1, 2, 4, 11, 11, 16 ];    let key = 11;    let n = arr.length;      document.write(binarySearchCount(arr, n, key));         // This code is contributed by rameshtravel07.</script>
5
Time Complexity: O(log(n)).Auxiliary Space: O(1).
This article is contributed by nuclode. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
jit_t
Brij Raj Kishore
Sakshi_Srivastava
Sach_Code
princiraj1992
andrew1234
princevishwakarma1
rameshtravel07
divyesh072019
amartyaghoshgfg
anandkumarshivam2266
Binary Search
Arrays
Arrays
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Introduction to Arrays
K'th Smallest/Largest Element in Unsorted Array | Set 1
Subset Sum Problem | DP-25
Introduction to Data Structures
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array
Find Second largest element in an array