Unilag Csc Forum > Programming
JAVA - Program to implement Linear Search
Page 1 / 1
JAVA - Program to implement Linear Search
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.
Quote   
04/05/2011 6:04 pm

Administrator
Cool Senior Member


Regist.: 04/04/2011
Topics: 14
Posts: 15
OFFLINE

Forum's a very good platform for helping ourselves. Please post your topics and comments

Endevour to check out our page Unilag Csc Page
http://www.facebook.com/pages/Unilag-Csc-Page/199688396730767 and like it.

Also join our new group Unilag Csc Group http://www.facebook.com/home.php?sk=group_173783495983164&ap=1 strictly computer scientists and aspirants too.
Quote   
Page 1 / 1
Login with Facebook to post
Preview