| 04/05/2011 6:03 pm |
 Administrator Cool Senior Member

Regist.: 04/04/2011 Topics: 14 Posts: 15
 OFFLINE | Hello there, you've finally made it to the section you've been waiting for.Note that the codes below are the solution to the problem above.
The java codes
public class Linear
{
/** Linear search for who in array a.
Precondition: a is not null
Postcondition: return a value k such that a[k] == who;
return -1 if there is no such k
*/
public static int linearSearch(int[] a, int who) {
for (int k = 0; k < a.length; k++) {
// who has not been found yet, i.e. all
// values a[0],a[1],...,a[k-1] are different than who
if (a[k] == who)
return k;
}
return -1;
}
public static void main (String[] args) {
int[] j = {5,7,2,3,8,4};
System.out.println("8 is at position " + linearSearch(j, 8));
System.out.println("6 is at position " + linearSearch(j, 6));
}
}
It would be best you understand what each line of code does by referring to the textbook. |
|
|