Algorithms in C#

This is part 3 of Algorithms questions in Interviews.(Part 1 | Part 2 )

In this post we will write an algorithm that finds an element in an array of infinite size.
How to find an element position from an array?

Below function takes an infinite size array and a key to be searched and returns first index position if found else -1. Here, we don’t know size of array and we can assume size to be infinite in this function.

Please note I am assuming the array is a sorted array. For (Quicksort) sorting the array you can refer to part 2 of this blog series.

First Occurence of element

private int FirstOccurrenceBinarySearch(int arr[], int low, int high, int data)
{
	int mid; 
	// A simple implementation of Binary Search
	if(high >= low)
	{
		mid = low + (high - low)/2; // To avoid overflow
		if((mid == low && arr[mid] == data) || (arr[mid] == data && arr[mid-1] < data)) 		{ 			return mid; 		} 		 		else if(arr[mid] >= data)
		{
			// We need to give preference to left part of the array
			// since we are concerned with the first occurrence
			return FirstOccurrenceBinarySearch(arr, low, mid-1, data);
		}
		else // We need to search in the right half
		{			
			return FirstOccurrenceBinarySearch(arr, mid+1, high, data);
		}
	}	
	return -1;
}

Last Occurence of element

		
private int LastOccurrenceBinarySearch(int[] array, int low, int high, int data)
{
	int mid;
	// A simple implementation of Binary Search
	if (high >= low)
	{
		mid = low + (high - low) / 2; // To avoid overflow
		if ((mid == high && array[mid] == data) || (array[mid] == data && array[mid + 1] > data))
			return mid;

		// We need to give preference to right part of the array
		// since we are concerned with the last occurrence
		else if (array[mid] <= data)
			return LastOccurrenceBinarySearch(array, mid + 1, high, data);
		else
			// We need to search in the left half
			return LastOccurrenceBinarySearch(array, low, mid - 1, data);
	}
	return -1;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s