(Ordered Sets) Programming Exercise 12 asks you to define the class unorderedSet
ID: 3599057 • Letter: #
Question
(Ordered Sets) Programming Exercise 12 asks you to define the class unorderedSetType to manipulate sets. The elements of an unorderedSetType object are distinct, but in no particular order. Design the class orderedSetType, derived from the class orderedArrayListType, to manipulate ordered sets. The elements of an orderedSetType object are distinct and in ascending order. Note that you need to redefine only the functions insert and replaceAt. If the item to be inserted is already in the list, the function insert outputs an appropriate message. Similarly, if the item to be replaced is already in the list, the function replaceAt outputs an appropriate message. Also, write a program to test your class.
Explanation / Answer
using namespace std;
class orderedSetType: public orderedArrayListType
{
public:
void insert(int item);
void replaceAt(int location, int item);
orderedSetType(int size=100);//Constructor
};
void orderedSetType::insert(int item)
{
if(length == maxSize){
cout << "Cannot insert in a full set.";
}else{
/* Perform binary search to check whether the item present in the list */
int first = 0;
int last = length - 1;
int middle = (first+last)/2;
while (first <= last) {
if (list[middle] < search)
first = middle + 1;
else if (list[middle] == item) {
cout << item << " already present in the Set";
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last){
/* item not present in the set. So insert it at location first */
for(int i=length; i=first; i--){
list[i]=list[i-1];
}
list[first]=item;
length++;
cout << item << " is inserted successfully";
}
}
}
void orderedSetType::replaceAt(int location, int item){
/* Perform binary search to check whether the item present in the list */
int first = 0;
int last = length - 1;
int middle = (first+last)/2;
while (first <= last) {
if (list[middle] < search)
first = middle + 1;
else if (list[middle] == item) {
cout << item << " already present in the Set";
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last){
/* item not present in the set. So replace the item at location */
list[location]=item;
cout << item << " is replaced successfully";
}
}
/* Testing the program */
int main(){
orderedSetType s;
int item, loc;
/* Test insert() function */
cout <<"Enter item to insert ";
cin >> item;
s.insert(item);
cout <<"Enter item to insert ";
cin >> item;
s.insert(item);
cout <<"Enter item to insert ";
cin >> item;
s.insert(item);
/* Test replaceAt() function */
cout <<"Enter item to replace ";
cin >> item;
cout <<"Enter location of replace ";
cin >> loc;
s.replaceAt(loc,item);
cout <<"Enter item to replace ";
cin >> item;
cout <<"Enter location of replace ";
cin >> loc;
s.replaceAt(loc,item);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.