-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecursionPractice-1[1].java
More file actions
81 lines (76 loc) · 2.3 KB
/
Copy pathRecursionPractice-1[1].java
File metadata and controls
81 lines (76 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
* PA39
* Sydni-Noel Levy-Davis
*/
package sorting;
public class RecursionPractice
{
/**
* Calculates value of a term in a Fibonacci sequence
* Precondition: n > 0.
* @param n an integer the represents the nth term in a sequence
* @return the value of nth term in the Fibonacci sequence
*/
public static int fib(int n)
{
if(n - 1 == 0)
return 1;
else if (n - 1 == 1)
return 1;
return fib(n-1) + fib(n-2);
}
/**
* Calculates gcd of two integers
* Precondition: neither integer parameters are 0.
* @param a an integer
* @param b an integer
* @return the gcd of the two numbers "a" and "b"
*/
public static int gcd(int a, int b)
{
int rem = a % b;
if (rem == 0)
return b;
return gcd(b,rem);
}
/**
* Finds index of a value in an integer array
* Precondition: array parameter is not null and is in ascending order
* @param arr an array of integers
* @param value an integer
* @return an index in which "value" appears in the array ( -1 if it doesn't appear).
*/
public static int binarySearch(int[] arr, int value)
{
int low = 0;
int high = arr.length - 1;
return binarySearch(arr, value, low, high);
}
/**
* Finds index of a value in an integer array
* Precondition: array parameter is not null and is in ascending order
* @param arr an array of integers
* @param value an integer
* @param low initial lower bound of the array being searched
* @param high initial upper bound of the array being searched
* @return an index in which "value" appears in the array ( -1 if it doesn't appear).
*/
private static int binarySearch(int[] arr, int value, int low, int high)
{
int median = (low + high) / 2;
if (low > high)
return -1;
else if (arr[median] == value)
return median;
else if (value > arr[median])
{
low = median + 1;
return binarySearch(arr, value, low, high);
}
else /*(value < arr[median])*/
{
high = median - 1;
return binarySearch(arr, value, low, high);
}
}
}