Recursive algorithm to find maximum

Hi there,
I am looking for a recursive algorithm for finding the maximum and minimum values in a double array.
I did find the code from this forum. It works upto the size of array=200 fine.. it however just waits and waits for larger size of the array.
The code I am using is:
public double maxRecursive(double [] array){
if (array.length==1){
     return array[0];
double [] next=new double[array.length-1];
System.arraycopy(array,1,next,0,array.length-1);
return Math.max(array[0],maxRecursive(next));
Could anyone help me with a better algorithm? I feel the above code is a overhaul with arraycopy as well as the recursive calls.
Thanks for all your help!
JP

try this exact code, and see the output (System.out.prints). That will explain you the logic.
public double maxRecursive(double [] array, int pos) {
     if (array.length - 1==pos) {
          System.out.println("So, I read all the elements, Final Value is :"+array[pos]+"\n");
          return array[pos];
     double recMax = maxRecursive(array, pos+1);
     System.out.println("Now I am at "+pos+" Position !!!\n");
     System.out.println("Till now my maximum value is : "+recMax+"\n");
     if(array[pos] > recMax) {
          System.out.println("My previous element is "+array[pos]+" since it is greater than my max value, here onwards, this will be my max value\n");
          return array[pos];
     else {
          System.out.println("My Previous element is "+array[pos]+" since it is less than my max value, my max value will not change\n");
          return recMax;
}Sudha

Similar Messages

  • Finding a non-recursive algorithm

    I had a project a year ago that was supposed to teach the class recursion. Already being familiar with the Java language, the project was simple.
    The project was, you ahve a "cleaning robot" which cleans an entire room and then returns to the spot it originally was. The room was inputed as a txt file. Everytime you moved to a spot it was automatically cleaned
    The Robot was given to you. The robot class hasthe following methods:
    void move(Direction)   - moves in the direction you gave it.
    boolean canMove(Direction)    -  returns true if the robot can move there without running into a wall
    boolean hasBeen(Direction) - returns true if the robot has cleaned the spot that is in that directionThe Direction class was given to you. It is an enumerated type with the Directions FORWARD, BACWARD, LEFT, RIGHT.
    now the Recursive algorithm is simple:
    private void clean(Direction c, Direction r)
                 move(c); //clean spot in direction
                 for(Direction d : Direction.values()) //go every direction
                      if(canMove(d) && !haveBeen(d)) clean(d,reverse(d));
                 move(r); //go back way we came
    private Direction reverse(Direction d)
                   switch(d)
                      case FORWARD:  d = Direction.BACKWARD; break;
                      case RIGHT:    d = Direction.LEFT;     break;
                      case BACKWARD: d = Direction.FORWARD;  break;
                      case LEFT:     d = Direction.RIGHT;    break;
                 return d;     
    public void start()
             clean(Direction.FORWARD, Direction.BACKWARD);
        }But I am curious how someone would go about implementing a NON recursive algorithm. I understand it would probably be around 2000 lines to implement it. I am not asking anyone to implement it, nor do I plan on it (well..I may one day if I am bored) I am only asking for mere curiosity how someone would go about implementing this non-recursively.
    I have thought about it and thought about it, and the only thing I come up with is recursion. What are your thoughts?

    then I think it'll work.Almost. Your algorithm is flawed in this section:
    move(c);
          // After everything else, come back.
           backtrace.push(reverse(c));What happens when c is the reverse direction? You add to the stack the reverse of the reverse. This means you will continually go back and forth in an infinite loop. I took what you started with and worked it into a working solution:
    private void cleanAll() {
              //imitate the call stack
              Stack<Stack<Direction>> call = new Stack<Stack<Direction>>();
              //holds all the reverse directions     
             Stack<Direction> backtrack = new Stack<Direction>();
             //starting stack
             Stack<Direction> start = new Stack<Direction>();
             //load the starting stack
             for (Direction d : Direction.values())
                  if(canMove(d) && !haveBeen(d))
                       start.push(d);
             call.push(start);
             while (!call.isEmpty()) {
                  Stack<Direction> s = call.pop();
                  while(!s.isEmpty()){
                       Direction c = s.pop();
                      move(c); //clean in this direction
                      backtrack.push(reverse(c)); //record the reverse
                      Stack<Direction> temp = new Stack<Direction>();
                      call.push(s); //stop the current path
                      //load the new stack
                      for (Direction d : Direction.values())
                         if (canMove(d) && !haveBeen(d))
                              temp.push(d);
                     if(!temp.isEmpty())   
                          s = temp; //make temp the current stack
             if(!backtrack.isEmpty())
                  move(backtrack.pop());// After everything else, come back.
        }The problem with your solution is that you use 1 stack for the entire process. In this case, it does not differentiate between moves, so it doesn't KNOW what is a reverse. You need to seperate the reverse directions and treat the different in the special case. In order to do that, you need to know WHEN to reverse. Well you reverse when you have completed a cleaning "path".
    My algorithm implements that "path" as another stack. And adds it to a stack of stacks. What this does is it allows me to know when to reverse. I pop off a stack from the call stack, and then after I am done with that stack I have to reverse, as shown in the code I posted.
    Thank you so much for enhancing my knowledge of Stacks. You have helped emensely. I will be sure to tell my professor that i implemented a iterative solution in about 50 lines of code (extremely lower than the 2000 he hypothosized)

  • How to find maximum number of users we can assign for Hyperion Planning.

    HI,
    How to find maximum number of users we can assign for Hyperion Planning.i.e., how to find license limit in hyperion planning 11.1.2.1.
    In Essbase propreties, the system is showing maximum planning users could be 65535.
    what would be the number for concurrent scenario?
    Thanks
    Giri
    Edited by: Giriprasad on Jun 18, 2012 2:18 AM

    The number of users would be based on your license agreement with Oracle, the system is not aware of your license agreement so it is up to you to stick to it.
    Cheers
    John
    http://john-goodwin.blogspot.com/

  • Help needed to write algorithm to find Direction given lat/lon

    Hello, i need an algorithm to find out the direction being traveled given the starting and ending lat/lon decimal coordinates. Anybody have any clues how to do it? or where i can find one to just plug into my program? thanks for your help
    public String getDirection(double prevLat, double prevLon, double newLat, double newLon) {
        String direction;
        return direction;
    }

    Perhaps this helps:
    http://www.cssd.ab.ca/tech/social/latitude/index.html
    It will help you learn the meaning of lat/long-coords. I think you will end up with somthing like this:
    if ( prevLat < newLat) {
       //we are travelling north
    else {
       // we are travelling south
    if (prevLong < newLong) {
       //we are travelling east?
    else {
       //we are travelling west
    }This could be wrong, since there is a west-long and an east-long..
    Anyhow, hope this gets you on your way.
    ps: is this a class-assignment??

  • Iterative and Recursive algorithms

    I am fairly new to Java and am currently looking into Data structures, algorithms etc...
    I have designed a very basic ADT (Abstract Data Type) class called Loan which contains the following private instance variables 'loanNo, copyNo, membershipNo, dateDueBack, totalFines'.
    Basically I am trying to devise an iterative and also a recursive algorithm for calculating fines for loans not returned over a given duration. For instance if I was to assume a fixed rate of say 1% for every day the book is overdue how would I go about writing the 2 algorithms.
    Both the algorithm and elements of the java code would be appreciated or any useful articles or websites that can help me to further my limited understanding of this topic.
    All help is greatly appreciated.

    I am very far from being an expert here, but:
    Two important things come to mind;
    1. Try to keep your calculations in one file/class it is tempting to have something like the following:
    class BookTypeA
      float calculateFine()
         loanRate = 2%;
         // stuff
    // and then in another file...
    class BookTypeB
      float calculateFine()
         loanRate = 0.5%;
         // stuff
    }Every time you update the algorithm for calculating the fines, you have to change both files, trust me, someone will notice if your calculations bend a penny one way or another.
    You solve this problem by having a Visitor, there is lots of stuff on the web about the Visitor pattern. Basically:
    class Calculator implements Visitor
       public int calculate( Book book  )
          //stuff here
    class BookTypeA extends Book
       void calculateFine(  Visitor v )
          v.visit( this );
    //main{}
    for(  Book bk : myBooks  )
        bk.calculateFine( calculator );
    // etc.2. Separate your calculations into discreet functions, notice the difference in the following two "calculators"...
    class Calculator
       float getFine( int daysoverdue )
          if(  !senior )
              float result = daysoverdue * 0.01f;
              result += ( int tax = result * 0.08f );
              result += ( previousFines );
              result -= ( float seniorsdiscount = result * 0.10f );
           //etc, etc.
    // The WAY BETTER version
    class Calculator
       float getFine( int daysoverdue )
          if(  !senior )
              float baseAmount = calculateBaseFines( daysoverdue );
              float taxAmount = calculateTax( baseAmount );
              float previousFines = addPreviousFines(  );
               float subTotal = baseAmount + taxAmount + previousFines;
              float seniorsDiscount = applySeniorsDiscount(  subTotal );
           //etc, etc.
          // one calculation per function
          float calculateTax(  float baseamount )
              taxRate = 0.08;
              return baseAmount * taxRate;
          // rest of the functions
    } In short be really explicit. Really clear. Chasing tax rates through program headers, global definitions, main classes is really rough. Put the tax rate right next to the calculation. Perform one calculation per function, stuff like this; int rate += ( amount * tax ) + zot; is impossible to debug.
    Hope that helps some.
    Andrew

  • True iterative algorithm/recursive algorithm

    Just confirming that the below is a true iterative algorithm
    public static double someMethod(int n, double t)
      if (n==0)   
        totalNo = n;  
      else  
        totalNo = number;    
        for (int i = 1; i < n; i++)       
          totalNo *= somePercentage;  
      return totalNo;
    }Recursive algorithms differ in the fact that they make a call to themselves. Is this true of any algorithm that makes a call to itself i.e. if an algorithm calls itself elsewhere in the algorithm it is always a recursive algorithm???
    Regards

    Not to be confused with dominition.You mean when Sue gets out her whip and stiletto
    heels?I think it refers to a control structure I once suggested. The traditional definition of recursion doesn't hold under concurrency! It's always implied that the caller waits for the recursive call to return. If it doesn't it's not true recursion. This happens when the recursive calls are spawned off in their own threads instead of beeing pushed onto a call stack.
    I called this dominition because I used the Domino Effect as an example. A domino piece starts to fall, gives the next piece a little push and then continues falling, and so on. I got a lot of flak for it because people couldn't accept to rethink the old definition of recursion and that I also had the nerve to invent a name for it. But the idea wasn't as novel as I first thought and it's also known as recursive parallelism or fork-join.
    Anyway dominition is interesting because by synchronizing the threads you can basically get pure iteration, pure recursion and everything in between. Also when multi-processor systems become more common there's room for new design patterns in wihich dominition probably will play a part.

  • Finding Maximum number

    Hi,
    I have 5 numbers like
    102 505 106 142 143
    and i want to find maximum number of them.
    i dont want to use select query or any internal table.
    is that any function regarding this ?
    Point will be awarded soon
    -R

    HI,
    use select max( field ) into max_fld from <dbtable>.
    rgds,
    bharat.

  • Hierholzers Algorithm to find the Euler tour

    Does anyone know how to use Hierholzers Algorithm to find a Euler tour of a graph with Java?
    Or anyone know of any sites that contain a program that already does this?
    Thanx

    Does anyone know how to use Hierholzers Algorithm to find a Euler tour of a graph with Java?The construction of an Euler tour is not that difficult. The core of the
    proof whether or not such a tour exists is the following lemma --
    An Euler tour exists if and only if every vertex has an even number of
    edges connected to it.
    Hierholzer came up with the following construction; for the sake of the
    example, we'll use this graph; A is the start/end vertex --     B-------D
       /|\     /|\
      / | \   / | \
    /  |  \ /  |  \
    A   |   /   |   F
    \  |  / \  |  /
      \ | /   \ | /
       \|/     \|/
        C-------E Note that all vertexes have an even degree, so an Euler tour can be
    constructed. Step /zero one in Hierholzer's construction is --
    0) let 'level' == 1; 'start' == A;
    1) Start at vertex 'start' and generate a random tour;
    This is easy, simply wander around over any unused edge until you reach
    vertex A again. Suppose we created the tour A -> B -> C -> A.
    2) label all the used edges using 'level' and remove all used edges;
    This leaves us with the following graph --     B-------D
         \     /|\
          \   / | \
           \ /  |  \
    A       /   |   F
           / \  |  /
          /   \ | /
         /     \|/
        C-------E Note that every vertex still has an even number of edges connected to it.
    3) For any vertex on the tour so far, find a vertex that still has unused
    edges. We randomly pick vertex B; if we can't find such vertex, goto step 5;
    4) level= level + 1; start= B; goto step 1;
    If we've reached this step for a second time we could have generated a tour
    B -> D -> E -> B. All the edges are removed, after labeling them with a
    level equal to 2. The resulting graph looks like this then --     B       D
    A       /       F
        C-------E It's not difficult to see that, after we get at step 4, we have to complete
    the last tour, say, D -> F -> E -> C -> D and we remove the corresponding
    edges after labeling them with a level equal to 3.
    Finally we arrive at this step --
    5) All edges are removed and we've collected three tours --
    level 1: A -> B -> C -> A
    level 2: B -> D -> E -> B
    level 3: D -> F -> E -> C -> D
    6) Walk the first level tour until you reach a vertex that connects to a higher
    level tour (at vertex B); leave the level 1 tour and follow the next level
    tour until a similar situation occurs. Apply this step continuously until
    you've reached your original starting vertex (A) again.
    You've found an Euler tour --
    This: A -> B -> C -> A expands to A -> B -> D -> E -> B -> C -> A.
    Which in turn expands to A -> B -> D -> F -> E -> C -> D -> E -> B -> C -> A.
    Et voila!
    kind regards,
    Jos

  • Modifying existing recursive algorithm to an iterative version

    Hi,
    I find myself wanting to modify the algorithm below to an iterative version or possibly one thats tail recursive because I'm getting stack overflow errors with the input i present my program. Can someone help me break this down? I've tried several approaches, and I seem to get stuck each time, not being able to express what I want appropriately without using recursion.
            public void visitAll(HeapItem hi) {
                HeapItem refs[] = hi.getReferences();
                HeapItem item;
                int i;
                hi.visited = true;
                for (i = 0; i < refs.length; ++i) {
                    item = refs;
    if (item != null && !item.visited)
    visitAll(item);

    You should do something like this...
    public void visitAll(HeapItem hi) {
                HeapItem refs[] = hi.getReferences();
                HeapItem item;
                int i;
                if(refs.length == 0) return;
                hi.visited = true;
                for (i = 0; i < refs.length; ++i) {
                    item = refs;
    if (item != null && !item.visited)
    visitAll(item);

  • Recursive algorithm design

    In this project you will find the longest increasing sequence in a two-dimensional area of positive integers that is stored in a file. For example, the following numbers maybe stored in the file matrix.dat.
    97 47 56 36 60 31 57 54 12 55
    35 57 41 13 82 80 71 93 31 62
    89 36 98 75 91 46 95 53 37 99
    25 45 26 17 15 82 80 73 96 17
    75 22 63 96 96 36 64 31 99 86
    12 80 42 74 54 14 93 17 14 55
    14 15 20 71 34 50 22 60 32 41
    90 69 44 52 54 73 20 12 55 52
    39 33 25 31 76 45 44 84 90 52
    94 35 55 24 41 63 87 93 79 24
    Your first task is to read the integers from the file in an array. Since you don't know how many numbers are stored in each line, you will need to use the nextLine method to read a whole line and then use the StringTokenizer class to find the number of integers per line. Assuming s is a line read from the file, the following code finds the number of integers in the line and stores it in length.
    StringTokenizer st = new StringTokenizer(s);
    int length=0;
    while (st.hasMoreTokens()) {
    st.nextToken();
    length++;
    Your next task is to find the longest increasing sequence, where a sequence starts at an integer and moves right or down to the next integer. The output of the program consists of a list of (row,column) items. In our case, one possible output will be as shown bellow, which also corresponds to the underlined numbers in the above area.
    Loading the matrix isn't a problem; I have that done. I understand the basic concepts of recursion; but I don't know how to figure this one out. Any suggestions? (And I don't need the exact answer; hints will help)

    When you start the recursive process at a certain position basically you will traverse a binary tree (you go either down or right in each position). The task is to find the longest sequence so you go through the matrix and note the maximum depth of the binary tree starting in each position of the matrix. You note the maximum depth for each position in a new matrix with the same dimension as the position matrix. The maximum depth at each position correspond to the longest path from the root to a leaf. This basically is the longest sequence starting at a position.
    Next you find the maximum length in the length matrix.
    Finally you go through the matrix and check which positions have the maximum length. At such positions you generate the binary trees again but this time you note the paths leading up to the maximum lengths. Note that there may be many of equal length, even starting in the same position.
    Well, the devil's in the details but I think this solution strategy should work.

  • How to find Maximum Record Count in a particular section

    Hi ALL
    My report has  3 detail sections. I am showing different set of data in each section.
    Example:
    Details a
    Details b
    Details c
    In the Details c section  I have 5 columns.
    I want to find out MAXIMUM RECORD COUNT in  only Details c.
    Actually I have done a running total on column1 field which gives me the records number in that section only. But I am not able to find the MAXIMUM record count.
    Rtotal   Colum1   Column 2 Column3
    1          Data1     Data2      Data3
    2          Data1     Data2      Data3
    3          Data1     Data2      Data3
    4          Data1     Data2      Data3
    Now I need the Maximum record count=4
    Thanks.

    If I have understood correctly you want to count the amount of records in each section.
    In this case, go to "Insert > Summary", choose your ID field, and choose "Count" in "Calculate this summary:". You can put the summary in your group footer.
    If you want the maximum (the highest number value in that column), you can choose "Maximum" instead of "Count".

  • Summing and Finding Maximum in 2d array

    So I have an 2d array of numbers and I am trying to find the maximum sum of the rows and give back the row number. So far I can get the sum and the maximum number but I need to give back the row number of the maximum value.
    public static void RowSumRow (int[][] table)
          static int sum[] = new int[5];
          int region=0;
          for (int row=0; row < table.length; row++)
                sum [row] = 0;
                for (int col=0; col < table[row].length; col++)
                   sum [row] = sum [row] + table[row][col];     
          int max = myMethods.maximumSearch(sum);
          System.out.println("The maximal revenue is $" + max + " at region " + region);
        }myMethods.maximumSearch
    public static int maximumSearch(int a[])
         int Max = a[0];
         for (int index=0; index < a.length; index++)
             if(Max < a[index])
              Max = a[index];
            return Max;
       }

    this is correct right?
    (the prarmeter rows is the rows that are to be tested)
    public static void RowSumRow (int[][] table, int rows)
          int sum[] = new int[rows];
          int region=0;
          for (int row=0; row < table.length; row++)
                sum [row] = 0;
                for (int col=0; col < table[row].length; col++)
                   sum [row] = sum [row] + table[row][col];     
          int max = myMethods.maximumSearch(sum);
          for(int x=0; x < sum.length; x++)
              if (max == sum[x])
                region = x-1;
          System.out.println("The maximal revenue is $" + sum[region] + " at region " + region);
        }This does what I want it to do right? Ive tested a few times and it is working, but is it logically correct?

  • Finding maximum Date in Cube

    Hi,
    How can I find the Maximum date from all the dates of a date characterstic which exists in CUBE Data.
    I want restrict a selection in my Query with this maximum Date. So how can i fetch that date into a variable?

    Hi
    You can call the function module RSDRI_INFOPROV_READ in your exit for the variable and read the dates and find the maximum. You have to pass the name of the info cube u want to read. However writing this code is slightly a tedious job. So think of any other way u can meet ur requirement.
    If you want to use the function module tell me i ll send u a piece of code which will give you an idea.
    Thanks
    Mansi

  • Recursive Algorithm for Postfix/Infix expressions

    For those that are unaware if infix is an expression like (5 + (3 * 2)) or (3 + 5) * 10, then the respective postfix expressions are 5 3 2 * + and 3 5 + 10 *.
    Basically I need to do two things if given a postfix expression: 1) determine if it's a valid postfix expression, and 2) if so, evaluate it.
    Now, I can (and did) do this with stacks easily. Very easy to understand with stacks. However, I need to do both using recursion, not stacks.
    I've tried to work out some kind of algorithm but what i'm doing just isn't working. Can someone help with the necessary algorithm needed for both methods? tia

    overrule wrote:
    TuringPest wrote:
    overrule wrote:
    This is an option many regulars here should consider. If you don't know, don't answer. Simple as that.i was attempting to be helpful. just because i misread doesnt mean i dont deserve to post here.
    way to be an internet thug though.No it's okay to be stupid. You can even be elected moderator if you can prove it.I thought you liked TuringPest? Well like might be a strong word...

  • Algorithm to find non repeating number from the list

    Hi,
    Can anybody provide me the algorithm for the program:
    User has provided a list of 'n' numbers (0-9) with only a single number not repeating at all and rest may repeat odd or even number of times. Now, job is to find out the number which is occuring only single time without repetition....

    Hi
    If n is a smallish number, then something like
    int bins[10];
    memset bins to zero;
    for (int i = 0; i < n; ++i)
    ++bins[arrayDigits[i]];
    for (int i = 0; i < 10; ++i)
    if (bins[i] == 1)
    printf("digit is %d\n", i);
    /* break if certain that i is the only bin == 1 */
    break;
    (arrayDigits is an array of the 'n' digits).
    If n is large, then you'll probably want to break out of that first loop as soon as only one of the bins.
    unsigned flag;
    unsigned first = 0US;
    unsigned second = 0US;
    for (int i = 0; i < n; ++i)
    flag = 1U << arrayDigits;
    if (first & flag)
    if (!(second & flag))
    /* second occurence of digit */
    second |= flag;
    /* exit condition is that 'first' has all bottom 10 bit set and
    'second' has all but 1 of the bottom 10 bits set */
    if (first == 0x3ff)
    /* all 'first' bits set */
    switch (second)
    case ~(1U << 0): /* digit is 0 */
    case ~(1U << 1): /* digit is 1 */
    case ~(1U << 9): /* digit is 9 */
    printf("digit is %d\n", i);
    break;
    default:
    /* do nothing - more than one digit still not at 'first' */
    /* else already seen 2 or more of digit */
    else
    /* first occurence of digit */
    first |= flag;
    I haven't tested any of the code.
    Paul

Maybe you are looking for

  • Safari crashes when trying to open files

    When I try to export any file to any application, for example, a PDF to iBooks, Safari crashes instantly and the iPad resets. I tried with different types of files and applications. Freezes everytime. Any ideas? Thanks

  • Centering Web template from Fireworks in Dreamweaver

    So, I created a web template in Fireworks and I imported the template into Dreamweaver.  I have been trying to center my webpage for quite some time now and every time I add a wrapper, it doesn't do anything.  It remains aligned to the left.  I delet

  • BAPI/FM for uploadng DATA in CS40

    Hi Any  BAPI/FM for uploadng DATA Thru CS40 T code Regards Rasheed

  • Please Help.  I can't uninstall Creative Suite 1.1

    Hi, I'm trying to uninstall Adobe Creative Suite through Programs and Features in Windows Vista, but everytime I try to uninstall it, I get an error right after I double click on the Adobe Creative Suite to unistall it.  This is the error that comes

  • Keypad won't stay open

    When I'm trying to type in numbers to get through an answering service, the keypad won't stay open. The screen actually goes blank while I'm typing. I have to press the button to get it to wake up, and, if I'm lucky, I can get another button pressed