Read the following code segment carefully and fill in blank #2. Read the documen
ID: 3722874 • Letter: R
Question
Read the following code segment carefully and fill in blank #2.
Read the documentation in the Pre/Post conditions carefully.
void SortedType::DeleteItem(ListItemType& item)
// Pre: List contains valid data and List is sorted by key using
// function ComparedTo.
// There is at most one list item with the same key as item;
// there may be none.
// Post: No list element has the same key as item.
// List is still sorted.
{
int location = 0;
int index;
bool moreToSearch;
moreToSearch = ______________; // 1
bool found = false;
while ( !found && _____________) // 2
{
switch (item.ComparedTo(info[location]))
{
case LESS : location++
moreToSearch = ______________________; // 3
break;
case GREATER : moreToSearch = ___________________; // 4
break;
case EQUAL : ________ = true // 5
break;
}
}
if (found)
{
for (index = location + 1; index < length; index++)
info[index - 1] = ______________; // 6
length--;
}
A) moreToSearch
B) !moreToSearch
C) None of these answers is correct.
Explanation / Answer
Below is the function DeleteItem with the filled blanks.
void SortedType::DeleteItem(ListItemType& item)
{
int location = 0;
int index;
bool moreToSearch;
moreToSearch = true; // 1
// the boolean variable moreToSearch will be set to true as the element to delete has to be found.
bool found = false;
while ( !found && moreToSearch ) // 2
{
switch (item.ComparedTo(info[location]))
{
case LESS : location++
moreToSearch = true ; // 3
// moreToSearch has to be set to true as the element is not yet found.
break;
case GREATER : moreToSearch = true ; // 4
// moreToSearch has to be set to true as the element is not yet found.
break;
case EQUAL : found = true; // 5
// found is set to true as the element is found. This would break the while loop.
break;
}
}
if (found)
{
for (index = location + 1; index < length; index++)
info[index - 1] = info[index]; // 6
// To delete the element, all the elements after it should be moved one element before.
length--;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.