The Algorithm Design Manual Chapter 4 Problem 33

Suppose that you are given a sorted sequence of distinct integers {a1 , a2 , . . . , an }.Give an O(lg n) algorithm to determine whether there exists an i index such as ai = i. For example, in {−10, −3, 3, 5, 7}, a3 = 3. In {2, 3, 4, 5, 6, 7}, there is no such i.

package avdongre.tadm;

public class ElementAtIndex {
	public int findElementAtIndex(int[] arr) {

		int low = 0;
		int high = arr.length - 1;
		while (low <= high) {
			int mid = (low + high) / 2;
			if (arr[mid] > mid + 1) {
				high = mid - 1;
			} else if (arr[mid] < mid + 1) {
				low = mid + 1;
			} else {
				return mid + 1;
			}
		}
		return -1;
	}

	public static void main(String[] args) {
		ElementAtIndex eai = new ElementAtIndex();
		{
			int[] arr = new int[] { 10, 20, 30, 40, 50 };
			System.out.println(eai.findElementAtIndex(arr));
		}
		{
			int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7 };
			System.out.println(eai.findElementAtIndex(arr));
		}
		{
			int[] arr = new int[] { 10, 1, 66, 5, 6, 7 };
			System.out.println(eai.findElementAtIndex(arr));
		}
		{
			int[] arr = new int[] { -10, -3, 3, 5, 7, 8, 11, 12 };
			System.out.println(eai.findElementAtIndex(arr));
		}

		{
			int[] arr = new int[] { -10, -3, 3, 5, 7 };
			System.out.println(eai.findElementAtIndex(arr));
		}
	}
}

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