help?? Write a method void orderedAdd (Integer pData) that will insert Integers
ID: 642096 • Letter: H
Question
help??
Write a method void orderedAdd (Integer pData) that will insert Integers
into a DList such that ascending sort order is maintained.
For example,
DList list = new DList(); // list = { }
list.orderedAdd(5); // list = { 5 }
list.orderedAdd(3); // list = { 3 5 }
list.orderedAdd(1); // list = { 1 3 5 }
list.orderedAdd(7); // list = { 1 3 5 7 }
list.orderedAdd(9); // list = { 1 3 5 7 9 }
list.orderedAdd(-5); // list = { -5 1 3 5 7 9 }
Answer//
public void orderedAdd(Integer pData) {
if (this.getSize() == 0) {
append(pData);
} else if (this.get(0) > pData) {
prepend(pData);
} else if (this.get(this.getSize() - 1) < pData) {
append(pData);
} else {
int i = 0;
while (this.get(i) < pData) {
i++;
}
this.add(i, pData);
}
}
Explanation / Answer
//only few lines of code can work
public void orderedAdd(Integer pData) {
int size=this.Count;
this.add(pData); //first add the integer to the end of the list
if(size >1)
{
this.Sort(); //then sort the list
}}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.