Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fast way of getting an index of an element in an array? [duplicate]

Tags:

java

c#

.net

I was asked this question in an interview. Although the interview was for dot net position, he asked me this question in context to java, because I had mentioned java also in my resume.

How to find the index of an element having value X in an array ?

I said iterating from the first element till last and checking whether the value is X would give the result. He asked about a method involving less number of iterations, I said using binary search but that is only possible for sorted array. I tried saying using IndexOf function in the Array class. But nothing from my side answered that question.

Is there any fast way of getting the index of an element having value X in an array ?

like image 979
teenup Avatar asked Aug 17 '10 08:08

teenup


2 Answers

As long as there is no knowledge about the array (is it sorted? ascending or descending? etc etc), there is no way of finding an element without inspecting each one.

Also, that is exactly what indexOf does (when using lists).

like image 175
f1sh Avatar answered Oct 03 '22 19:10

f1sh


How to find the index of an element having value X in an array ?

This would be fast:

int getXIndex(int x){
    myArray[0] = x;
    return 0;
}
like image 33
Ultimate Gobblement Avatar answered Oct 03 '22 21:10

Ultimate Gobblement