I'm trying to make an algorithm which checks my array and returns the total amount of different values. I wrote my code, but it gives me wrong answer. Could anyone just check my code and see what I've done wrong?
public static int differentValues(int[] array] {
int n = array.length;
int total = 0;
if(n < 1) return total;
// This checks if array is sorted or not
for(int i = 0; i < n-1; i++) {
if(a[i] > a[i+1]) System.out.println("Array not sorted!");
}
// This should calculate the amount of total different values
for(int i = 0; i < n-1; i++) {
if(a[i] != a[i+1]) total++;
}
return total;
}
If my array is [1,1,2,3] I should get 3 as output, but my code gives me 2... What have I done wrong?
Edit: Both if-statements should be in same for loop, I just had to test with different values in for loop.

New Topic/Question
Reply



MultiQuote






|