Tuesday, June 23, 2015

[Coding Quiz] Find count of a repeated value in a sorted array



http://www.geeksforgeeks.org/count-number-of-occurrences-in-a-sorted-array/


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodingTest.SortSearch
{
    class Program
    {

        static int count(int[] arr, int x)
        {
            int i;
            int j;

            /* get the index of first occurrence of x */
            i = first(arr, 0, arr.Length - 1, x, arr.Length);

            /* If x doesn't exist in arr[] then return -1 */
            if (i == -1)
                return i;

            /* Else get the index of last occurrence of x. Note that we
                are only looking in the subarray after first occurrence */
            j = last(arr, i, arr.Length - 1, x, arr.Length);

            /* return count */
            return j - i + 1;
        }

        /* if x is present in arr[] then returns the index of FIRST occurrence
           of x in arr[0..n-1], otherwise returns -1 */
        static int first(int[] arr, int low, int high, int x)
        {
            if (high >= low)
            {
                int mid = (low + high) / 2;  /*low + (high - low)/2;*/
                if ((mid == 0 || x > arr[mid - 1]) && arr[mid] == x)
                    return mid;
                else if (x > arr[mid])
                    return first(arr, (mid + 1), high, x, n);
                else
                    return first(arr, low, (mid - 1), x, n);
            }
            return -1;
        }


        /* if x is present in arr[] then returns the index of LAST occurrence
           of x in arr[0..n-1], otherwise returns -1 */
        static int last(int[] arr, int low, int high, int x)
        {
            if (high >= low)
            {
                int mid = (low + high) / 2;  /*low + (high - low)/2;*/
                if ((mid == arr.length - 1 || x < arr[mid + 1]) && arr[mid] == x)
                    return mid;
                else if (x < arr[mid])
                    return last(arr, low, (mid - 1), x, n);
                else
                    return last(arr, (mid + 1), high, x, n);
            }
            return -1;
        }

        static void Main(string[] args)
        {
            int[] arr = { 1, 2, 2, 3, 3, 3, 3 };
            int x = 3;

            int c = count(arr, x);
            Console.WriteLine(" {0} occurs {1} times ", x, c);

            Console.Read();
        }
    }
}

No comments:

Post a Comment