Results 1 to 2 of 2
- 03-16-2011, 03:52 PM #1
Member
- Join Date
- Mar 2011
- Posts
- 2
- Rep Power
- 0
Using Linear Search to find multiple indexes
Okay first of all, yes this is homework which I have been asked to complete. Help which I am asking for with this is to simply point me in the right direction.
What I have asked to do is to use linear search to find a value in an array (let's say for example that the number was 6) and then to find all of the indexes in which 6 appears in the array.
int[] a = [3, 2, 6, 1, 0, 0, 6]
so the result which I should receive should be 2 and 6 as those are the positions in which 6 appears. (Also need a return value if it isn't in the list but I can do that.)
My logic is to run a for loop in the method that is responsible for searching the array and to print it. This does work but my issue here now is that -1 (this is the flag that says that the value is not present in the array) is always returned to the main method which means that as far as the program is concerned, every time the program is executed, there are never any indexes found from the search.
Example of what is printed on screen:
[3, 2, 6, 1, 0, 0, 6]
enter a value to search:> 6
2 6 The specific value which you have searched for is not present in this array.
I hope I have been clear and thank you for your time.
-
In case you are unfamiliar with "printf", the first %d is replaced by searchTerm, and the second %d is replaced by i, and %n makes a line break like "println" does.Java Code://define list to search int[] a = {3, 2, 6, 1, 0, 0, 6}; //define number to find in list int searchTerm = 6; //define a List because we don't know how many answers there will be so we can't use an Array java.util.List<int> answer = new java.util.ArrayList<int>(); //for each integer item in the array "a"; int i=a for (int i:a) { //if i=6, add to our List if (i == searchTerm) answer.add(i); } //print our list using the Java Formatter for (int i:answer) { System.out.printf("We found %d at location %d%n",searchTerm,i); }Last edited by ozzyman; 03-16-2011 at 04:39 PM.
Similar Threads
-
binary search...multiple datatypes?
By TopNFalvors in forum New To JavaReplies: 8Last Post: 03-15-2011, 08:03 PM -
Search function with multiple hits and ability to chose what hit is correct?
By pecca-ve in forum New To JavaReplies: 3Last Post: 01-10-2011, 01:54 AM -
problem with linear search
By Metastar in forum New To JavaReplies: 14Last Post: 09-14-2010, 08:01 PM -
Problem with linear search
By Metastar in forum New To JavaReplies: 2Last Post: 09-14-2010, 06:28 AM -
Please help me with this program (Linear Search two arrays)
By Meta in forum New To JavaReplies: 1Last Post: 03-11-2010, 12:49 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks