Java Program to find the number of occurrences of a given number using Binary Search approach

This is a Java Program to find number of occurences of a given number using binary search approach. The time complexity of the following program is O (log n).

Here is the source code of the Java program to find number of occurences of a given number using binary search approach. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

/*
 *    Java Program to Find the Number of occurrences of a given Number using Binary Search approach
 */
 
import java.util.Scanner;
 
public class NumberOfOccurences
{
    public static void main(String[] args) 
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter number of elements in sorted array");
        int N = scan.nextInt();
        int[] arr = new int[ N ];
        /* Accept N elements */
        System.out.println("Enter "+ N +" sorted elements");
        for (int i = 0; i < N; i++)
            arr[i] = scan.nextInt();
        System.out.println("Enter number to find occurences");
        int num = scan.nextInt();
 
        int f = occur(arr, num);
        if (f == -1)
            System.out.println("No occurence");
        else 
            System.out.println("Occurences = "+ f);
    }    
    public static int occur(int[] arr, int num)
    {
        /* find first index */
        int l1 = first(arr, num);
        /* find last index */
        int l2 = last(arr, num);
        if (l1 == -1 || l2 == -1)
            return -1;
        return l2 - l1 + 1;
    }
    public static int first(int[] arr, int num)
    {
        if (arr[0] == num)
            return 0;
        int start = 0, end = arr.length - 1;
        int mid = (start + end) / 2;
        int flag = 0;
        while (!(arr[mid] == num && arr[mid - 1] < arr[mid]))
        {
            if (start == end)
            {
                flag = 1;
                break;
            }
            if (arr[mid] >= num)
                end = mid - 1;
            if (arr[mid] < num)
                start = mid + 1;
            mid = (start + end) / 2;
        }
        if (flag == 0)
            return mid;
        return -1;        
    }
    public static int last(int[] arr, int num)
    {
        if (arr[arr.length - 1] == num)
            return arr.length - 1;
        int start = 0, end = arr.length - 1;
        int mid = (start + end) / 2;
        int flag = 0;
        while (!(arr[mid] == num && arr[mid + 1] > arr[mid]))
        {
            if (start == end)
            {
                flag = 1;
                break;
            }
            if (arr[mid] > num)
                end = mid - 1;
            if (arr[mid] <= num)
                start = mid + 1;
            mid = (start + end) / 2;
        }
        if (flag == 0)
            return mid;
        return -1;        
    }
}
Enter number of elements in sorted array
10
Enter 10 sorted elements
1 1 3 3 3 3 4 4 4 5
Enter number to find occurences
3
Occurences = 4
 
 
Enter number of elements in sorted array
10
Enter 10 sorted elements
1 1 3 3 3 3 4 4 4 5
Enter number to find occurences
5
Occurences = 1

Related posts:

Java Program to implement Priority Queue
Java Program to Generate Date Between Given Range
Java Optional as Return Type
Các nguyên lý thiết kế hướng đối tượng – SOLID
Java Program to Create the Prufer Code for a Tree
Java Program to Implement Warshall Algorithm
Java Program to Represent Graph Using Incidence Matrix
Binary Search
Introduction to Apache Commons Text
Java Program to Perform Inorder Recursive Traversal of a Given Binary Tree
Java Program to Implement Quick Sort with Given Complexity Constraint
Collect a Java Stream to an Immutable Collection
Java Program to Implement Queue using Two Stacks
Marker Interface trong Java
Java Program to Implement Triply Linked List
Các kiểu dữ liệu trong java
Filtering a Stream of Optionals in Java
Java Program to Check whether Undirected Graph is Connected using BFS
Java Byte Array to InputStream
REST Web service: Tạo ứng dụng Java RESTful Client với Jersey Client 2.x
Spring Boot - Twilio
XML Serialization and Deserialization with Jackson
Spring Cloud AWS – Messaging Support
Spring Security – Reset Your Password
Netflix Archaius with Various Database Configurations
Java Program to Use Dynamic Programming to Solve Approximate String Matching
Java Program to Implement TreeSet API
LinkedList trong java
Vấn đề Nhà sản xuất (Producer) – Người tiêu dùng (Consumer) và đồng bộ hóa các luồng trong Java
Custom HTTP Header with the HttpClient
Java Program to Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph
Chuyển đổi giữa các kiểu dữ liệu trong Java