B. Consider a problem to find the student who had the highest GPA for the 2020/2021 academic year. Using the below data set, answer the questions that follow: StudentGPA[2,2.5,4,4,4,3,3.5,3.3,3.1,2.1] i. Explain how a binary search algorithm can be used to solve this problem. [2.5 marks] ii. Explain how a sorting algorithm can be used to solve this problem. [2.5 marks] iii. Write the algorithm using the binary implementation. [2.5 marks] iv. Write the algorithm using the sorting implementation. [2.5 marks
i. Binary search cannot be used to solve this problem, since it is used to search for a specific element in a sorted array, and since you need to find the maximum value that is unknown, then binary search cannot be used in this case.
ii. Sort the array and display the last or first element (depending on how to sort) this will be the maximum value in the array.
iii.
public static int binarySearch(double value, double[] array) {
int left = 0;
int right = array.length - 1;
int middle;
while (left <= right) {
middle = (left + right) / 2;
if (value < array[middle]) {
right = middle - 1;
} else if (value > array[middle]) {
left = middle + 1;
} else {
return middle;
}
}
return -1;
}
iv.
public static void sort(double[] array) {
int minI;
double tmp;
for (int i = 0; i < array.length; i++) {
minI = i;
for (int j = i + 1; j < array.length; j++) {
if (array[minI] > array[j]) {
minI = j;
}
}
tmp = array[minI];
array[minI] = array[i];
array[i] = tmp;
}
}
Comments
Leave a comment