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);
}
}
}
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