Skip to content

Commit f498c44

Browse files
ch08p2
1 parent 5c5a989 commit f498c44

2 files changed

Lines changed: 58 additions & 1 deletion

File tree

‎ch08/ArrayExamples.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ public static void main(String[] args) {
7575
System.out.println(indexOfMax(array));
7676
System.out.println(sieve(5));
7777
System.out.println(areFactors(24,array));
78-
System.out.println(areFactors(24,array));
78+
System.out.println(arePrimeFactors(24,array));
7979
}
8080

8181
/**

‎ch08/Histogram.java‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,61 @@ public static int inRange(int[] a, int low, int high) {
3030
return count;
3131
}
3232

33+
/**
34+
* This method finds the maximum value
35+
* in an int array, but
36+
* only considering the elements
37+
* between lowIndex and highIndex,
38+
* two given integers, including both.
39+
* @param array an int array
40+
* @param lowIndex the minimum value considered
41+
* @param highIndex the maximum value considered
42+
* @return the maximum element in the range if found,
43+
* an error message and a fake number otherwise
44+
*/
45+
public static int maxInRange(int[] array, int lowIndex, int highIndex){
46+
int max, max1, max2;
47+
if(lowIndex==highIndex){ //base case
48+
max = array[lowIndex];
49+
}
50+
else {
51+
int count = 0;
52+
if(highIndex-lowIndex==1){
53+
max1=maxInRange(array,lowIndex,lowIndex);
54+
max2=maxInRange(array,highIndex,highIndex);
55+
if(max1>=max2)
56+
max = max1;
57+
else
58+
max = max2;
59+
}else {
60+
int halfInterval = highIndex - (highIndex - lowIndex) / 2;
61+
max1 = array[lowIndex];
62+
for (int i = lowIndex; i < halfInterval; i++) {
63+
if (array[i] > max1) {
64+
max1 = array[i];
65+
}
66+
}
67+
max2 = array[halfInterval];
68+
for (int i = halfInterval; i < highIndex; i++) {
69+
if (array[i] > max2) {
70+
max2 = array[i];
71+
}
72+
}
73+
if (max1 > max2)
74+
max = maxInRange(array, lowIndex, halfInterval);
75+
else if (max2 > max1)
76+
max = maxInRange(array, halfInterval, highIndex);
77+
else
78+
max = max1;
79+
}
80+
}
81+
return max;
82+
}
83+
84+
public static double max(int[] a){
85+
return maxInRange(a, 0, a.length - 1);
86+
}
87+
3388
public static void main(String[] args) {
3489
int numValues = 8;
3590
int[] array = randomArray(numValues);
@@ -54,6 +109,8 @@ public static void main(String[] args) {
54109
for (int score : scores) {
55110
counts[score]++;
56111
}
112+
113+
System.out.println(maxInRange(array,2,5));
57114
}
58115

59116
}

0 commit comments

Comments
 (0)