Sunday, 30 October 2016

Algorithms :- Find maximum in array with the two approaches present in algorithms

      Algorithms has two types of approaches either iterative or recursive. Have a look at below example where we will solve problem in both the approaches.


package com.algorithms.iterative;

public class FindMaxInArray {

public static void main(String[] args) {
          int a[] = {2,42,1 };
          //Iterative approach
          long time = System.currentTimeMillis();
          int max=a[0];
          for(int i=1;i<a.length;i++){
         if(max<a[i]){
         max=a[i];
         }
          }
          System.out.println((System.currentTimeMillis()- time));
          System.out.println("Max value :- "+ max);
         //Recursive approach
          System.out.println("Max value using recursive :- "+ maxArray(a,a.length,1,a[0]));
         
         
}

public static int  maxArray(int[] a,int length,int currentCount,int max){
        if(currentCount>=length){
        return max;
        }  
if(max<a[currentCount]){
        return  maxArray(a,length,currentCount+1,a[currentCount]);
        }else{
        return  maxArray(a,length,currentCount+1,max);
        }
}

}

No comments:

Post a Comment

Custom single threaded java server

 package com.diffengine.csv; import java.io.*; import java.net.*; import java.util.Date; public class Server { public static void main(Str...