Reputation: 63
I have a problem in execution of a java program which counts the longest sorted array but the result is always equal to initial value max = 1
, where can be the problem?
package longestsortedsquence;
public class Longestsortedsquence {
public static void main(String[] args) {
int[] arry={3,98,274,943,23,56,23,4};
System.out.print(longestsortedsequence(arry));
}
public static int longestsortedsequence(int[] arry){
if(arry==null){
return 0;
}
int max=1;
int len=1;
for(int i=0;i<arry.length-1;i++){
if(arry[i]<=arry[i+1]){
len=len++;
}
else{
len=1;
}
if(max<len){
max=len;
}
}
return max;
}
}
Upvotes: 1
Views: 57
Reputation: 5742
problem is len
package longestsortedsquence;
public class Longestsortedsquence {
public static void main(String[] args) {
int[] arry={3,98,274,943,23,56,23,4};
System.out.print(longestsortedsequence(arry));
}
public static int longestsortedsequence(int[] arry){
if(arry==null){
return 0;
}
int max=1;
int len=1;
for(int i=0;i<arry.length-1;i++){
if(arry[i]<=arry[i+1]){
len=len++;<---- change it to `len++`
}
else{
len=1;
}
if(max<len){
max=len;
}
}
return max;
}
}
Upvotes: 0
Reputation: 73
len++
will return len
, and the side effect of that function increase 1 tolen
.
You should use len++
or len=++len
, but the second option is not recommended.
Upvotes: 1
Reputation: 174
Don't use len=len++;
Use len++;
only instead.
You can see explanation for this here : What is x after "x = x++"?
Upvotes: 2