Merge pull request #1406 from shellhub/dev

Update max and findMax function
This commit is contained in:
Yang Libin 2020-08-10 17:03:52 +08:00 committed by GitHub
commit 5fd352f84e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 31 additions and 7 deletions

View File

@ -5,7 +5,7 @@ public class FindMax {
//Driver
public static void main(String[] args) {
int[] array = {2, 4, 9, 7, 19, 94, 5};
System.out.println("max = " + findMax(array));
assert findMax(array) == 94;
}
/**

View File

@ -6,7 +6,8 @@ public class FindMaxRecursion {
int low = 0;
int high = array.length - 1;
System.out.println("max value is " + max(array, low, high));
assert max(array, low, high) == 94;
assert max(array, array.length) == 94;
}
/**
@ -27,6 +28,17 @@ public class FindMaxRecursion {
int leftMax = max(array, low, mid); //get max in [low, mid]
int rightMax = max(array, mid + 1, high); //get max in [mid+1, high]
return leftMax >= rightMax ? leftMax : rightMax;
return Math.max(leftMax, rightMax);
}
/**
* Get max of array using recursion algorithm
*
* @param array contains elements
* @param len length of given array
* @return max value of {@code array}
*/
public static int max(int[] array, int len) {
return len == 1 ? array[0] : Math.max(max(array, len - 1), array[len - 1]);
}
}

View File

@ -5,7 +5,7 @@ public class FindMin {
//Driver
public static void main(String[] args) {
int[] array = {2, 4, 9, 7, 19, 94, 5};
System.out.println("min = " + findMin(array));
assert findMin(array) == 2;
}
/**

View File

@ -2,11 +2,12 @@ package Maths;
public class FindMinRecursion {
public static void main(String[] args) {
int[] array = {2, 4, 9, 7, 19, 94, 5};
int[] array = {2, 4, 9, -7, 19, 94, 5};
int low = 0;
int high = array.length - 1;
System.out.println("min value is " + min(array, low, high));
assert min(array, low, high) == -7;
assert min(array, array.length) == -7;
}
/**
@ -27,6 +28,17 @@ public class FindMinRecursion {
int leftMin = min(array, low, mid); //get min in [low, mid]
int rightMin = min(array, mid + 1, high); //get min in [mid+1, high]
return leftMin <= rightMin ? leftMin : rightMin;
return Math.min(leftMin, rightMin);
}
/**
* Get min of array using recursion algorithm
*
* @param array contains elements
* @param len length of given array
* @return min value of {@code array}
*/
public static int min(int[] array, int len) {
return len == 1 ? array[0] : Math.min(min(array, len - 1), array[len - 1]);
}
}