Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Check to see if an array is sorted

Status
Not open for further replies.

ToN10

Programmer
Feb 2, 2006
2
US
Hey guys,

Ok, basically, I had to copy an array of integers that another class sent to mine, and then do various things to it. The final thing I have to do is have the method sorted() check the array (localArray) to see whether or not it is sorted. (Ascending and Descending both count as sorted, no order what-so-ever doesnt.) The method then returns true if it is sorted, and false if it is not sorted. I sounds so simple for me, but I'm not sure why this isnt working. Here is the code I wrote:


public boolean sorted( ){
for(int i=0;i<50;i++){
if(localArray<localArray[i+1]){
return true;}
else if(localArray>localArray[i+1]){
return true;}
else{
return false;} //by this point, the return statement should be set.
}
//compiler wants a return statement here(apparently the set statment above does not count.
}

Any idea's? Thanks.
 
Using your code:
Code:
public boolean sorted( ){
 boolean ascending = false;
 int first = localArray[0];
 int second = localArray[1];
 if(second > first) //ascending
  ascending = true;

 for(int i=1; i<49; i++) //note:  assumes [49] is last index
 {
  if((ascending && localArray[i] > localArray[i+1]) || (!ascending && localArray[i] < localArray[i+1]))
   return false;
 }

 return true;
}

If it fails the test one time, it returns false. If it passes through the for-loop without returning false, it returns true.

Is this what you're after?

Dave


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience! [infinity]
 
Just a hint. If you plan to sort the array if it's not already sorted, I think it's easier to order it anyway.

If it's already ordered, the operation will be really low cost.

Cheers,
Dian
 
thanks Dave, that works! i definitely would have never guessed to do it like that, but i can see how it works, and how mine was never going to work like it was. thanks again.

and dian, i actually did not want to sort it, so yeah. thanks for the reply though.

good forums. :)
 
'glad that did it for you!

Have a great day!

Dave


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience! [infinity]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top