A).Consider a problem to find the student who had the highest GPA for the 2020/2021 academic year.
i. Explain your choice of either a search or a sorting algorithm to solve this problem. [7.5 marks]
ii. Write the algorithm for your implementation. [7.5 marks]
B). Consider the analogy of a pile of books on a table. Using a diagram, explain the basic operations involved in adding a book to the pile and removing a book from the pile. [5 marks]
C). Use the code below to answer the questions that follow: [5 marks]
public class CS204 { public static int linearSearch(int[] data, int target) {
for (int i = 0; i < data; i++) {
if (target == data[i]){
return i;
}
}
return -1;
}
public void main(String[] args) {
int[] data = {3, 14, 7, 22, 45, 12, 19, 42, 6}; System.out.println("Search for 7: " + linearSearch(7));
}
}
i). Why is method linearSearch declared static? Identify and resolve the errors in the code.
ii) identify nd resolve the errors in the code.
A.
1. The complexity of a linear search is O(n), the complexity of sorting is O(nlogn), so it is obvious that to find the maximum element it is better (if you are supposed to search for an element in the array once) to use a linear search.
2.
B. Copying elements within an array, copying elements into a new array, adding an element to an array.
C.
public class CS204 {
public static int linearSearch(int[] data, int target) {
for (int i = 0; i < data.length; i++) {
if (target == data[i]) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
int[] data = {3, 14, 7, 22, 45, 12, 19, 42, 6};
System.out.println("Search for 7: " + linearSearch(data, 7));
}
}
Comments
Leave a comment