java - Finding Max of an array using Recursion -


so it's pretty simple find max of array using loop or while loop, wanted try out recursion. reason, substring doesn't work - says "cannot find symbol". why this? strategy continue subdividing , comparing 2 sides until there 1 left should max....am doing right? thanks

   public static int max(int[] array) {      if (array.length == 1) {         return array[0];     } else {         int mid = (array.length) / 2;         int leftmax = max(array.substring(0, mid));         int rightmax = max(array.substring(mid, array.length));         if (leftmax > rightmax) {             return leftmax;         } else {             return rightmax;         }      } } 

since array of type int[] not string, cannot use substring(). instead, keep track of indexes searching through. copying array each iteration waste of both space , time.

int max( int[] array ){ return max( array, 0, array.length - 1 ); }  int max( int[] array, int low, int high ) {     if (low == high) {         return array[low];     }      else {         int mid = (high + low) / 2;         int leftmax = max(array, low, mid );         int rightmax = max(array, mid, high );         if (leftmax > rightmax) {             return leftmax;         }          else {             return rightmax;         }      } } 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -