Results 1 to 6 of 6
Thread: search array - ascending order
- 08-28-2012, 01:36 PM #1
Member
- Join Date
- Aug 2012
- Posts
- 3
- Rep Power
- 0
search array - ascending order
hi, I got a problem with searching ordered array. So far the code below works only for unordered array.
int findItem = 11, pos = 0;
int [] list = {35, 12, 27, 18, 45, 16, 38, 11}; // unordered array
boolean found = false;
while (pos < list.length && found == false)
{
if (list[pos] == findItem){
found = true;
}
else
{
++pos;
}
} // while
if (found) {
System.out.println("Found at position: " + (pos +1));
}
else {
System.out.println("NOT Found");
}
this works fine, but if I change the array to search in ascending order it doesnt.
int findItem = 33, pos = -1;
int [] list = {12, 18, 22, 33, 45, 48, 77, 89}; // Ordered
Can anyone explain it to me ? how should I correct it? thank you for help
- 08-28-2012, 01:47 PM #2
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,545
- Rep Power
- 11
Re: search array - ascending order
In the second case you start with pos as -1, not 0.
I'd expect an ArrayIndexOutOfBounds exception on list[pos]==findItem. But that's only a guess without seeing runnable code.
- 08-28-2012, 02:01 PM #3
Member
- Join Date
- Aug 2012
- Posts
- 3
- Rep Power
- 0
Re: search array - ascending order
yes, just a mistake, pos should = 0 in the second case. I changed that but it still doesnt work.
- 08-28-2012, 02:19 PM #4
Re: search array - ascending order
Can you post a small complete program that compiles, executes and shows the problem?it still doesnt work.If you don't understand my response, don't ignore it, ask a question.
- 08-28-2012, 02:38 PM #5
Member
- Join Date
- Aug 2012
- Posts
- 3
- Rep Power
- 0
Re: search array - ascending order
public class JdemoFindArray
{
public static void main(String[] args)
{
int findItem = 33, pos = 0;
int [] list = {12, 18, 22, 33, 45, 48, 77, 89}
boolean found = false;
while (pos < list.length && found == false)
{
if (list[pos] == findItem){
found = true;
}
else
{
++pos;
}
} // while
if (found) {
System.out.println("Found at position: " + (pos +1));
}
else {
System.out.println("NOT Found");
}
}
} // JdemoFindArray
it outputs message "NOT Found'' even though 33 is in a array
- 08-28-2012, 03:09 PM #6
Similar Threads
-
Sorting in ascending and descending order
By flpanthers1 in forum New To JavaReplies: 10Last Post: 06-27-2011, 03:48 PM -
ascending order using array rush
By jca in forum New To JavaReplies: 2Last Post: 01-03-2011, 04:24 AM -
Checking ascending order of array
By counterfox in forum New To JavaReplies: 3Last Post: 10-22-2010, 10:44 PM -
How to add coins in ascending order in arraylist
By tribujohn in forum New To JavaReplies: 2Last Post: 01-23-2009, 04:31 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks