Count 1s in a Sorted Binary Array

PHOTO EMBED

Tue Feb 08 2022 13:38:59 GMT+0000 (Coordinated Universal Time)

Saved by @Uttam #java #gfg #geeksforgeeks #lecture #searching #sortedarray #count1s

import java.util.*;
import java.io.*;

class GFG 
{ 
	static int countOnes(int arr[], int n)
	{
		int low = 0, high = n - 1;

		while(low <= high)
		{
			int mid = (low + high) / 2;

			if(arr[mid] == 0)
				low = mid + 1;
			else
			{
				if(mid == 0 || arr[mid - 1] == 0)
					return (n - mid);
				else 
					high = mid -1;
			}
		}

		return 0;		
	}

	public static void main(String args[]) 
    {
        int arr[] = {0, 0, 1, 1, 1, 1}, n = 6;

		System.out.println(countOnes(arr, n));   // OUTPUT : 4

    } 

}
content_copyCOPY