Sample Input #1
isSorted([1,3,5,7})
Sample Output #1
true
Sample Input #2
isSorted({11,9,2,-5})
Sample Output #2
true
Sample Input #3
isSorted({1,2,3,4,-1,-2})
public boolean isSorted(int[] arr){
boolean isSorted = false;
if(arr.length==1)
return true;
for(int i=0;i<arr.length-1;i++)
{
if(arr[i]<arr[i+1])
{
isSorted = true;
}
else if(arr[i]>arr[i+1])
{
isSorted = true;
}
else
isSorted = false;
if(isSorted != true)
return isSorted;
}
return isSorted;
}
What happens to my code some of my testcase didn't pass parameter '{24,27,30,31,34,37,40,42}' pass parameter '{1,3,5,7,4}' fail
You are trying to use a single boolean
variable to keep two bits of information, which does not work. You need two boolean
s here - one to indicate that the array is sorted in ascending order, and another one to indicate that the array is sorted in descending order.
Prepare two variables, isAscending = true
and isDescending = true
. Go through the array the way you do now, and set the corresponding variable to false
if you detect an inversion. Never set these variables to true
again, because a single inversion breaks the sort order.
if (arr[i]<arr[i+1]) isDescending = false;
if (arr[i]>arr[i+1]) isAscending = false;
That's all you need to do. Once the loop is over, isAscending || isDescending
isAscending || isDescending
expression gives you the answer.
To speed up an exit from your for
loop, use this termination condition:
i<arr.length-1 && (isAscending || isDescending)
Logic:
I have a different proposition than the one from Andreas :
ascending
and descending
to true
ascending = ascending && previousElement <= currentElement
ascending || descending
ascending || descending
You need another var to indicate the sorting:ascending or descending
short srt = 0;//-1 descending, +1ascending
then compare the two first val to decide the sorting sense, so I propose this solution:
public boolean isSorted(int[] arr){
short srt = 0;//-1 descending, +1ascending
if(arr.length <= 2)
return true;
else {
if(arr[0] < arr[1])
srt = 1;
else
srt = -1
for(int i=1;i<arr.length-1;i++)
if((arr[i] < arr[i+1] && srt = -1) || (arr[i] > arr[i+1] && srt = 1)
return false;
}
return true;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.