27 November 2011

Given a sorted array, find k in least possible time in Java

Given a sorted array and a value k, write a program to find whether that number is present in that array or not.

The first solution that comes to the mind for this problem is to traverse through the entire array and find whether it is having the value k and return true or false. This takes O(n) running time. But then, we are presented with a hint that the input array is sorted (lets assume in ascending order). This problem can be attacked by doing a divide and rule analysis.

This can be done recursively. See whether k is inbetween the last and first element in the array. If it is, then divide the array into two and repeat the same. If its not, simply return false. Yes, its as simple as that. Following is the java code for the same.

Leave some comments if you have anything to say.



Unknown said...

Isn't this just a regular binary search? Sorry if I'm missing something...

BragBoy said...

@Pin-Sho Feng : What do you mean by binary search ?

There is something called as binary search tree where you will first have to construct a BST which will take time more than O(n). Once its constructed, you can find the value in O(log n) time,

But that is a different ballgame in this scenario. You will have to find k with least possible time which implicitly says you cannot waste any time at all.

Hope I was clear. Let me know if you have any questions.

Unknown said...

By binary search I mean this:

In this case, an iterative version would be faster (in Java at least), avoiding some recursion overhead.

bragadeesh said...

@Pin-Sho Feng : Got it. Appreciate the link ! And yeah iteration and recursion always have trade off in terms of clarity, overhead and ease of understanding.

Thanks for stopping by!

Faz said...

this is coded very similar to a binary search function.

BragBoy said...

@Faz - you are right.. good observation