Docsity

Solution to Quiz 6 of CMSC 131 Spring 2005 - Adding Students to an Array, Quizzes of Computer Science

Toggle sidebar
bg1
CMSC 131 Spring 2005 Quiz 6 Solution
One possible solution to this problem is given below. Note that you are required to
create a student copy (duplicate) and to add students appropriately when there are
no students initially. Addition of a student when there are already some existing
students requires finding the correct position for insertion and creation of a new
array at the end.
public void add(Student student) {
Student duplicate = new Student(student);
Student[] newArray = null;
if (array == null) {
array = new Student[1];
array[0] = duplicate;
}
else {
newArray = new Student[array.length + 1];
int startCopyingIndex = 0;
if (student.getPriority() < array[0].getPriority()) {
/* To the end of the list */
newArray[newArray.length - 1] = duplicate;
} else {
/* To the beginning of the list */
newArray[0] = duplicate;
startCopyingIndex = 1;
}
/* Copying the elements from the original array */
for (int i=0, k=startCopyingIndex; i<array.length; i++) {
newArray[k++] = array[i];
}
array = newArray;
}
}

Partial preview of the text

Download Solution to Quiz 6 of CMSC 131 Spring 2005 - Adding Students to an Array and more Quizzes Computer Science in PDF only on Docsity!

CMSC 131 Spring 2005 Quiz 6 Solution

One possible solution to this problem is given below. Note that you are required to create a student copy (duplicate) and to add students appropriately when there are no students initially. Addition of a student when there are already some existing students requires finding the correct position for insertion and creation of a new array at the end.

public void add(Student student) { Student duplicate = new Student(student); Student[] newArray = null; if (array == null) { array = new Student[1]; array[0] = duplicate; } else { newArray = new Student[array.length + 1]; int startCopyingIndex = 0; if (student.getPriority() < array[0].getPriority()) { /* To the end of the list / newArray[newArray.length - 1] = duplicate; } else { / To the beginning of the list */ newArray[0] = duplicate; startCopyingIndex = 1; }

/* Copying the elements from the original array */ for (int i=0, k=startCopyingIndex; i<array.length; i++) { newArray[k++] = array[i]; }

array = newArray; } }