Answer to Question #175378 in Java | JSP | JSF for Lucy

Question #175378

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.


1
Expert's answer
2021-03-26T20:10:42-0400

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.

  1. save to the variable max the first element of the array
  2. in a loop starting from the second element of the array for all elements
  3. compare current element to variable max
  4. if the current element is greater than the variable max, store the current element in max.

B. Copying elements within an array, copying elements into a new array, adding an element to an array.

C.

  1. The developer decided to make the method a class method, for this he used the statics modifier.
  2. the loop condition does not have access to the length of the array(data.length), there is no static modifier in the main method(public static void main(String[] args) ), missing 1 parameter when calling the search method(linearSearch(data, 7))
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));
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog