Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to search an element

Recently I had an interview, where they asked me a "searching" question.
The question was:

Assume there is an array of (positive) integers, of which each element is either +1 or -1 compared to its adjacent elements.

Example:

array = [4,5,6,5,4,3,2,3,4,5,6,7,8]; 

Now search for 7 and return its position.

I gave this answer:

Store the values in a temporary array, sort them, and then apply binary search.

If the element is found, return its position in the temporary array.
(If the number is occurring twice then return its first occurrence)

But, they didn't seem to be satisfied with this answer.

What is the right answer?

like image 346
NSUser Avatar asked Dec 27 '15 14:12

NSUser


People also ask

How will you search an element in the most efficient manner?

I gave this answer: Store the values in a temporary array, sort them, and then apply binary search. If the element is found, return its position in the temporary array.

Which searching technique is best?

Binary search method is considered as the best searching algorithms. There are other search algorithms such as the depth-first search algorithm, breadth-first algorithm, etc. The efficiency of a search algorithm is measured by the number of times a comparison of the search key is done in the worst case.

Which searching technique is better when the elements are not sorted?

If you're going to search very often, it's usually better to sort, then use a binary search (or, if the distribution of the contents if fairly predictable, an interpolation search).

Which search is faster in the unsorted data structure?

Which is the fastest search algorithm for unsorted array? If the array is not sorted then you have to search for the element by iteration ,linear search . There is no better way than O(n).


1 Answers

You can do a linear search with steps that are often greater than 1. The crucial observation is that if e.g. array[i] == 4 and 7 hasn't yet appeared then the next candidate for 7 is at index i+3. Use a while loop which repeatedly goes directly to the next viable candidate.

Here is an implementation, slightly generalized. It finds the first occurrence of k in the array (subject to the +=1 restriction) or -1 if it doesn't occur:

#include <stdio.h> #include <stdlib.h>  int first_occurence(int k, int array[], int n);  int main(void){     int a[] = {4,3,2,3,2,3,4,5,4,5,6,7,8,7,8};     printf("7 first occurs at index %d\n",first_occurence(7,a,15));     printf("but 9 first \"occurs\" at index %d\n",first_occurence(9,a,15));     return 0; }  int first_occurence(int k, int array[], int n){     int i = 0;     while(i < n){         if(array[i] == k) return i;         i += abs(k-array[i]);     }     return -1; } 

output:

7 first occurs at index 11 but 9 first "occurs" at index -1 
like image 184
John Coleman Avatar answered Sep 29 '22 14:09

John Coleman