forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
ff6b5c7
commit 5043f89
Showing
2 changed files
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
package Maths; | ||
|
||
public class FindMaxRecursion { | ||
public static void main(String[] args) { | ||
int[] array = {2, 4, 9, 7, 19, 94, 5}; | ||
int low = 0; | ||
int high = array.length - 1; | ||
|
||
System.out.println("max value is " + max(array, low, high)); | ||
} | ||
|
||
/** | ||
* Get max of array using divide and conquer algorithm | ||
* | ||
* @param array contains elements | ||
* @param low the index of the first element | ||
* @param high the index of the last element | ||
* @return max of {@code array} | ||
*/ | ||
public static int max(int[] array, int low, int high) { | ||
if (low == high) { | ||
return array[low]; //or array[high] | ||
} | ||
|
||
int mid = (low + high) >>> 1; | ||
|
||
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; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
package Maths; | ||
|
||
public class FindMinRecursion { | ||
public static void main(String[] args) { | ||
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)); | ||
} | ||
|
||
/** | ||
* Get min of array using divide and conquer algorithm | ||
* | ||
* @param array contains elements | ||
* @param low the index of the first element | ||
* @param high the index of the last element | ||
* @return min of {@code array} | ||
*/ | ||
public static int min(int[] array, int low, int high) { | ||
if (low == high) { | ||
return array[low]; //or array[high] | ||
} | ||
|
||
int mid = (low + high) >>> 1; | ||
|
||
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; | ||
} | ||
} |