Question

[C++] Create two functions that receive an integer list by reference and an integer you want...

[C++] Create two functions that receive an integer list by reference and an integer you want to look for, then have them both return an iterator pointing to the target integer that is being looked for. One function must implement a linear search and at the other must implement a binary search. Test both in main function.

The Function Prototypes are as Follows:

list<int>::iterator searchListLinear(list<int>& arg, int target);
list<int>::iterator searchListBinary(list<int>& arg, int target);
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks

#include<iostream>

#include<list>

using namespace std;

//method to find the iterator pointing to target in arg list, returns the end() if not found

list<int>::iterator searchListLinear(list<int>& arg, int target){

                //looping and checking each element sequentially

                for(list<int>::iterator it=arg.begin();it!=arg.end();it++){

                                if(*it==target){

                                                //found, returning iterator

                                                return it;

                                }

                }

                //not found

                return arg.end();

}

//method to find the iterator pointing to target in arg list, this time using binary search

//assuming elements are sorted in ascending order

list<int>::iterator searchListBinary(list<int>& arg, int target){

               

                list<int>::iterator it;

                //finding lowest and highest positions

                int low=0, high=arg.size()-1;

                int mid;

                //looping as long as low<=high

                while(low<=high){

                                //finding middle index

                                mid=(low+high)/2;

                                /**

                                                Now this is a bit of tricky way. the problem with list type is that we cannot

                                                get a random access iterator, means we cannot 'jump' to a position in list

                                                directly. we can only move forward or backward one position at a time till

                                                we reach the target position. So binary search is not so efficient for list type.

                                */

                                //creating an iterator, pointing to beginning

                                it=arg.begin();  

                                //advancing the iterator mid number of times forward, so that it will be at position 'mid'

                                for(int i=0;i<mid;i++){

                                                it++;

                                }

                                //comparing current element with target

                                if(*it==target){

                                                //found, returning the iterator

                                                return it;

                                }else if(*it<target){

                                                //will search the right half

                                                low=mid+1;

                                }else{

                                                //will search the left half

                                                high=mid-1;

                                }

                               

                }

                return arg.end(); //not found

}

int main(){

                //creating a list of integers (sorted, otherwise binary search wouldn't work)

                list<int> int_list={1,3,5,7,9,11,22,33,44};

                list<int>::iterator it;

                //displaying list

                cout<<"list: ";

                for(it=int_list.begin();it!=int_list.end();it++){

                                cout<<*it<<" ";

                }

                cout<<endl;

               

                //searching for an element that exists using searchListLinear

                cout<<"Searching for 22 using searchListLinear"<<endl;

                it=searchListLinear(int_list,22);

                //displaying result

                if(it==int_list.end()){

                                cout<<"Not found!"<<endl;

                }else{

                                cout<<"Found! Value at returned iterator: "<<*it<<endl;

                }

               

                //searching for an element that does not exist using searchListLinear

                cout<<"Searching for 19 using searchListLinear"<<endl;

                it=searchListLinear(int_list,19);

                if(it==int_list.end()){

                                cout<<"Not found!"<<endl;

                }else{

                                cout<<"Found! Value at returned iterator: "<<*it<<endl;

                }

               

                //searching for an element that exists using searchListBinary

                cout<<"Searching for 33 using searchListBinary"<<endl;

                it=searchListBinary(int_list,33);

                if(it==int_list.end()){

                                cout<<"Not found!"<<endl;

                }else{

                                cout<<"Found! Value at returned iterator: "<<*it<<endl;

                }

               

                //searching for an element that does not exist using searchListBinary

                cout<<"Searching for 6 using searchListBinary"<<endl;

                it=searchListBinary(int_list,6);

                if(it==int_list.end()){

                                cout<<"Not found!"<<endl;

                }else{

                                cout<<"Found! Value at returned iterator: "<<*it<<endl;

                }

               

                return 0;

}

/*OUTPUT*/

list: 1 3 5 7 9 11 22 33 44

Searching for 22 using searchListLinear

Found! Value at returned iterator: 22

Searching for 19 using searchListLinear

Not found!

Searching for 33 using searchListBinary

Found! Value at returned iterator: 33

Searching for 6 using searchListBinary

Not found!

Add a comment
Know the answer?
Add Answer to:
[C++] Create two functions that receive an integer list by reference and an integer you want...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a program (a3.py) that has 3 function definitions: magic-sequential(), magic-binary(), and main(). You will write...

    Write a program (a3.py) that has 3 function definitions: magic-sequential(), magic-binary(), and main(). You will write the code for the above functions. Both magic functions (magic-sequential() and magic-binary()) will look for a magic index in a given sorted list of distinct integers. A magic index in a list myList[0 ... n-1] is defined to be an index i such that myList[i] = i . Both functions receive the list as a parameter and return an integer: either the magic index,...

  • DO NOT use for loop and while loop Goal: Learn how to use recursive functions. General...

    DO NOT use for loop and while loop Goal: Learn how to use recursive functions. General requirement: Use cout to fully demonstrate your works for all tasks. The output must clearly show how each of these functions work. If no output is displayed for a task below, 0 point will be given to the task. If the output is not clear, some points may be deducted.    Task 1 – Reverse array (3 pts) Given an integer array like: const...

  • Problem 2 (USE C++) Assume you are given two functions: a function that returns –in a...

    Problem 2 (USE C++) Assume you are given two functions: a function that returns –in a variable passed by reference- the GCD of all integer numbers in an array void GCD(int A[], int size, int &g) and another function that allows you to divide all numbers of an array by a given integer void Div(int A[], int size, int gcd) (assume the functions are in a library, therefore you don’t need to implement them, but just use them). 1. Write...

  • IN C ONLY PLZ (read the instruction carefully plz) You will implement the following functions: List...

    IN C ONLY PLZ (read the instruction carefully plz) You will implement the following functions: List * initIntegerList( ) // Return empty list int insertAtHead(int k, List*) // Insert k at head int insertAtTail(int k, List*) // Insert k at tail int removeHead(List *) // Remove head and return its key int getListSize(List *) // Return number of elements in list void printHead(List *) // Print key in head void moveHeadToTail(List *) // Move key at head to tail This...

  • Write a C++ program In this assignment you will complete the definition of two functions that...

    Write a C++ program In this assignment you will complete the definition of two functions that implement the repeated squaring algorithm described in the Stamp textbook on pages 98-99. Note that your implementation should not use the pow() function, the powl() functions, or any other built-in exponentiation functions. program4-driver.cpp - This file contains a completed main() function that serves as the driver to parse the command line, pass the values to the powerModN() function, and print the result. Make no...

  • CE – Return and Overload in C++ You are going to create a rudimentary calculator. The...

    CE – Return and Overload in C++ You are going to create a rudimentary calculator. The program should call a function to display a menu of three options: 1 – Integer Math 2 – Double Math 3 – Exit Program The program must test that the user enters in a valid menu option. If they do not, the program must display an error message and allow the user to reenter the selection. Once valid, the function must return the option...

  • C++ LAB 19 Construct functionality to create a simple ToDolist. Conceptually the ToDo list uses a...

    C++ LAB 19 Construct functionality to create a simple ToDolist. Conceptually the ToDo list uses a structure called MyToDo to hold information about each todo item. The members of the MyToDo struct are description, due date, and priority. Each of these items will be stored in an array called ToDoList. The definition for the MyToDo struct should be placed in the header file called ToDo.h Visually think of the ToDoList like this: There are two ways to add items to...

  • Create a CPP file for a C++ Program. Write exactly these functions, power(x,y) function and a...

    Create a CPP file for a C++ Program. Write exactly these functions, power(x,y) function and a print(text, number) function and the main() function. The power(x,y) function returns an integer result that is calculated by raising a number x (integer) to a power y (integer). The second argument y (exponent) of the function can not exceed 100. If the second argument exceeds 100, the function should return -1. Your power(x,y) function must be able to take either 1 or 2 integer...

  • c++ Write two versions of a function that returns a dynamic array consisting of all prime...

    c++ Write two versions of a function that returns a dynamic array consisting of all prime numbers less than or equal to the int parameter n. You may declare the dynamic array to have length n, even though this is a bit inefficient. In one version of the function, return the number of primes via a separate reference variable. In the other, use 0 as a sentinel value to signify the end of the prime list. See below for the...

  • Create a function that takes a list and an integer v, and returns True if v...

    Create a function that takes a list and an integer v, and returns True if v is in the list (False otherwise). The function should be efficient and stop searching as soon as possible. •The main program must generate a very large list with random elements, call the function to search a value and display the result. Add in the function a variable Nsteps to count the number of steps used by the algorithm (number of times the loop is...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT