• Post Reply Bookmark Topic Watch Topic
  • New Topic

Help in Linear Search  RSS feed

 
Imam Bux Mallah
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey friends,

I am stuck in this program below.
I am supposed to get the result of the item whether it's in array of not. Kindly guide me through this...where I have done the mistake.
I am new in Java.

__________________________________________________ _____________________

 
Ernie Mcracken
Ranch Hand
Posts: 33
Mac Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

You've got a few problems with it...

This will give you a compile time error because you haven't opened the curly brace for the else.


This will give you an array index out of bounds exception at runtime because you are trying to put something into an element of an array that doesn't exist.





 
Greg Brannon
Bartender
Posts: 563
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another approach to code a linear search (more straightforward?) is to use a for loop:



Several variations of the above are possible, depending on the requirements. For example, if all you have to show is success or failure, you could print "Successful" as a result of the if statement, or you could set a success flag - many options.
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Greg Brannon wrote: . . . use a for loop: . . .
That is probably the commonest way to do it. I have enhanced your code by adding a return value. Now it returns the array index for the first place the element was found (ignoring the possibility there might be several identical values in the array), or -1 for "not found". This has been the conventional way to represent "found" and "not found" since C was developed about 40 years ago, and maybe longer than that.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!