Find the highest odd number in an array using recursion in java

Rizky Tri :
public static int highestOdd(int [] arr, int index)
{
  if(arr.length-1 == index) return arr[index];
  int high = highestOdd(arr,index+1);
  high = high > arr[index] ? high : arr[index];
  return high;
}

the index always passes as 0, so this code will check all the numbers including even numbers but I just want to output the highest odd number. I hope somebody will help me Thanks before.

Md Golam Rahman Tushar :

While replacing the value of high with arr[index] if arr[index] value is higher just check if the value is odd. Else keep the high value as it is. Try the following code. It will return -1 if there have no odd value in the array(assuming all the values of array are positive, if there have possibility of negative value then you can replace -1 with integer min). Let me know if you don't understand any part.

public static int highestOdd(int [] arr, int index) {
   if(arr.length - 1 == index) return arr[index] % 2 > 0 ? arr[index] : -1;
   int high = highestOdd(arr,index+1);
   if(arr[index] % 2 > 0) high = high > arr[index] ? high : arr[index];
   return high;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=170686&siteId=1