Each object in a collection called items has two variables, a String name and an int number. The collection is ordered in ascending order of number.
The collection supports the following methods:
- isEmpty()
- getFirst()
- getNext()
- getNthObject(int n)
- hasNext()
- length()
- insertAtStart(Obj o)
- insertAtEnd(Obj o)
- insertAtN(int n, Obj o)
- Write an algorithm using a for loop that prints the names of each object (4 marks)
- Write an algorithm using a while loop that prints the names of each object (4 marks)
- Write an algorithm that inserts an object o at the correct place in the list (6 marks)
- Write an algorithm to sort the collection in descending order (2 marks)
My Answers below. These aren’t the only right answers. There are lots of different ways you can code these.
(a)
for(int i = 0; i < items.length(); i++){ System.out.println(items.getNthObject(i).name); }
(b)
if (!items.isEmpty()) { System.out.println(items.getFirst().name); while(items.hasNext()){ System.out.println(items.getNext().name); } }
(c)
if (items.isEmpty()){ items.insertAtStart(o); } else { Object tmp = items.getFirst(); count = 0; while (items.hasNext()){ count++; if (o.number > items.getNthObject(count).number){ items.insertAt(count, o); } }
(d) for (int i = 0; i < items.length(); i++) { items.insertAtStart(items.getNthObject(i)); }