Logo 
Search:

Java Article

Submit Article
Comments on Program to search an element in an array using Linear Search
Category: Java (Arrays)    Author: Easy Tutor

A Java Program to search an element in an array using Linear Search.


Yemi Ade
Yemi Ade from United StatesMar 03
Dear tutor,

This is not a comment but I need help to solve below problem

Start with this array of unsorted names. You can copy and paste it directly into your Java file. Do not change the names or the order in which they appear. Use this array exactly as it is here, otherwise your results will not match the expected results. DO NOT make this array global, I want you to pass it as a parameter to the methods that will use it.

String[] names = { "fred" , "barney", "tom", "jerry", "larry", "moe", "curly",
"betty" , "wilma", "bart", "homer", "marge", "maggie", "lisa",
"pebbles" , "bambam", "smithers", "burns", "milhouse", "george", "astro",
"dino" , "mickey", "minnie", "pluto", "goofy", "donald", "huey",
"louie" , "dewey", "snowwhite", "happy", "doc", "grumpy", "sneezy",
"dopey" , "sleepy", "bambi", "belle", "gaston", "tarzan", "jane",
"simba" , "scar", "mufasa", "ariel", "flounder", "bugs", "daffy",
"elmer" , "foghorn", "chickenhawk", "roger", "jessica", "hank", "bobby",
"peggy" , "spot", "pongo", "perdy", "buzz", "potatohead", "woody",
"chuckie" , "tommy", "phil", "lil", "angelica", "dill", "spike",
"pepe" , "speedy", "yosemite", "sam", "tweety", "sylvester", "granny",
"spiderman" , "batman", "superman", "supergirl", "robin", "catwoman","penguin",
"thing" , "flash", "silversurfer", "xmen", "pokemon", "joker", "wonderwoman"
};


Write your own Linear Search method that takes an array as a parameter and returns the number of comparisons to find the item:

int linearSearch ( String [ ] namesarray )
In the main method of the program write a simple loop that enters a name to search for and reports the number of comparisons it took to find that one name and an average count for ALL the searches conducted. When the user enters the name "exit" or "quit", leave the loop and the program will stop execution.

Example:

Enter a name to search for: tarzan
Linear search: 62 comparisons, average 42 comparisons per linear search


Do not make the variables used to calculate the average global, and make sure to use integer arithmetic ( no decimal point ). Test your program, obviously the average will match the first search, but verify your calculation for the second and third search using a calculator.

Do not move on to the next phase until you are sure your linearSearch and average calculation are working properly.

Thanks


Please enter your Comment
  • Comment should be atleast 15 Characters.
  • Please put code inside [Code] your code [/Code].