Question

Add binary_search() (page 462) to your program. Modify main() to prompt the user for a number...

Add binary_search() (page 462) to your program. Modify main() to prompt the user for a number to search (until ^D) and display the position of the number in the sorted vector. Try your program for the following user input:

1
15
18
40
30
50
^D 

The output should be:

-1
2
-1
7
5
-1 

int binary_search(vector<int> v, int from, int to, int value)
{
if (from > to)
return -1;
int mid = (from + to) / 2;
if (v[mid] == value)
return mid;
else if (v[mid] < value)
return binary_search(v, mid + 1, to, value);
else
return binary_search(v, from, mid - 1, value);
}

#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
//selection sort function prototype
void selectionSort(vector<int>&v);
//Main method
int main()
{
   //file read object
   ifstream file;
   //vector declaration
   vector<int>numbers;
   //name of the filr given the object to open
   file.open("sort.txt");
   //file is not found error
   if (!file) {
       cout << "File not found" << endl;
       return 0;
   }
   //Other wise read file data and store in a vector
   else {
       while (!file.eof()) {
           int line;
           if (file >> line){
               numbers.push_back(line);
           }

       }
       //Vector values before sort
       cout << "Before sorting:" << endl;
       for (int i = 0; i < numbers.size(); i++) {
           cout << numbers[i] << " ";
       }

       cout << endl;
   }
   //call sort function
   selectionSort(numbers);
   cout << "After sorting:" << endl;
   //Vector values after sort
   for (int i = 0; i < numbers.size(); i++) {
       cout << numbers[i] << " ";
   }

   cout << endl;

    return 0;
}
//Selection sort implementation
void selectionSort(vector<int> &v) {
   int vecsize = v.size();
   for (int i = 0; i < vecsize-1; i++)
       for (int j = i + 1; j < vecsize; j++)
           if (v[i] > v[j])
               swap(v[i], v[j]);
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

PLASE GIVE THUMBS UP, THANKS, FOR ANY QUERY LEAVE COMMENT.

AS YOUR sort.txt file is not given in question so i can't execute according to your input because it will not give that exact location.

i create my own list and input. you can check on your given sort.txt it will work 100% smooth

SAMPLE OUTPUT:

CODE :

#include<iostream>
#include<fstream>
#include<vector>
#include <cstdlib>
using namespace std;
//selection sort function prototype
void selectionSort(vector<int>&v);
int binary_search(vector<int> v, int from, int to, int value);
//Main method
int main()
{
//file read object
ifstream file;
//vector declaration
vector<int>numbers;
//name of the filr given the object to open
file.open("sort.txt");
//file is not found error
if (!file) {
cout << "File not found" << endl;
return 0;
}
//Other wise read file data and store in a vector
else {
while (!file.eof()) {
int line;
if (file >> line){
numbers.push_back(line);
}
}
//Vector values before sort
cout << "Before sorting:" << endl;
for (int i = 0; i < numbers.size(); i++) {
cout << numbers[i] << " ";
}
cout << endl;
}
//call sort function
selectionSort(numbers);
cout << "After sorting:" << endl;
//Vector values after sort
for (int i = 0; i < numbers.size(); i++) {
cout << numbers[i] << " ";
}
cout << endl;
int value;
while(1)
{
    cout<<"Enter number to search : ";
    if(cin>>value){
   }
    else
    break;
    cout<<binary_search(numbers,0,numbers.size()-1,value)<<endl;
}

return 0;
}
//Selection sort implementation
void selectionSort(vector<int> &v) {
int vecsize = v.size();
for (int i = 0; i < vecsize-1; i++)
for (int j = i + 1; j < vecsize; j++)
if (v[i] > v[j])
swap(v[i], v[j]);
}

int binary_search(vector<int> v, int from, int to, int value)
{
if (from > to)
return -1;
int mid = (from + to) / 2;
if (v[mid] == value)
return mid;
else if (v[mid] < value)
return binary_search(v, mid + 1, to, value);
else
return binary_search(v, from, mid - 1, value);
}

Add a comment
Know the answer?
Add Answer to:
Add binary_search() (page 462) to your program. Modify main() to prompt the user for a number...
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
  • Practical 5: Write a program that implements several sorting algorithms, and use it to demonstrate the comparative perfo...

    Practical 5: Write a program that implements several sorting algorithms, and use it to demonstrate the comparative performance of the algorithms for a variety of data sets. Need Help With this Sorting Algorithm task for C++ Base Code for sorting.cpp is given. The header file is not included in this. Help would be much appreciated as I have not started on this due to personal reasons #include <cstdlib> #include <iostream> #include <getopt.h> using namespace std; long compares; // for counting...

  • Update your first program to dynamically allocate the item ID and GPA arrays. The number of...

    Update your first program to dynamically allocate the item ID and GPA arrays. The number of items will be the first number in the updated “student2.txt” data file. A sample file is shown below: 3 1827356 3.75 9271837 2.93 3829174 3.14 Your program should read the first number in the file, then dynamically allocate the arrays, then read the data from the file and process it as before. You’ll need to define the array pointers in main and pass them...

  • Selection sort is often the first sorting algorithm covered in introductory computer science courses. Java code...

    Selection sort is often the first sorting algorithm covered in introductory computer science courses. Java code that uses selection sort to place the elements of an integer array into non-decreasing order is shown here: public void swapNumbers(int i, int j) { ​int temp = numbers[i];​ /* put numbers[i] somewhere to keep it safe */ ​numbers[i] = numbers[j]; /* put numbers[j] at index i */ ​numbers[j] = temp;​ /* put numbers[i] at index j */ } public void selectionSort(int[] numbers) {...

  • Am I getting this error because i declared 'n' as an int, and then asking it...

    Am I getting this error because i declared 'n' as an int, and then asking it to make it a double? This is the coude: #include "stdafx.h" #include <iostream> #include <fstream> #include <string> #include <algorithm> #include <vector> using namespace std; void sort(double grades[], int size); char calGrade(double); int main() {    int n;    double avg, sum = 0;;    string in_file, out_file;    cout << "Please enter the name of the input file: ";    cin >> in_file;   ...

  • I wrote a card shuffle program and I am trying to see how I can add...

    I wrote a card shuffle program and I am trying to see how I can add a sorting function to the program to sort the players hands before printing them. How would I do this? #include <iostream> #include <iomanip> #include <vector> #include <algorithm> using namespace std; void printHand(int []); void deal(vector<int> &, int[], int[], int[], int[]); void unwrapDeck(vector<int> &deck) { for(int i=0; i<=51; i++) deck.push_back(i); } void shuffleDeck(vector<int> &deck) { //Status of cards before shuffling cout << "Before shuffling: "...

  • An easier way to do the Binary Search part or a simplistic way for beginners. Not...

    An easier way to do the Binary Search part or a simplistic way for beginners. Not using such high code for the assignment in general also commenting on what each line does. COMMENT ON the code below .what does each part do for the program? and a better and more simple and basic way to do binary search and get same results. #include <iostream> #include <fstream> using namespace std; void swap(int *xp, int *yp) { int temp = *xp; *xp...

  • Hi there. I tried to submit this before, but the copy/paste didn't copy my vectors correctly....

    Hi there. I tried to submit this before, but the copy/paste didn't copy my vectors correctly. Hello there. I am trying to implement the djikstras shortest path algorithm into my code in C++ with a vector of vectors. However, when I test I get an error "Exception thrown at 0x75FFC762 in graphMain.exe: Microsoft C++ exception: std::out_of_range at memory location 0x009CF26C" for line 115 in graph.cpp. Could you help me debug? I am so close! ----------------------------FILE NAME: pch.h--------------------------------------- // pch.cpp: source...

  • I need help of how to include the merge sort code into this counter code found...

    I need help of how to include the merge sort code into this counter code found below: #include<iostream> using namespace std; int bubble_counter=0,selection_counter=0; // variables global void bubble_sort(int [], int); void show_array(int [],int); void selectionsort(int [], int ); int main() { int a[7]={4,1,7,2,9,0,3}; show_array(a,7); //bubble_sort(a,7); selectionsort(a,7); show_array(a,7); cout<<"Bubble counter = "<<bubble_counter<<endl; cout<<"Selection Counter = "<<selection_counter<<endl; return 0; } void show_array(int array[],int size) { for( int i=0 ; i<size; i++) { cout<<array[i]<< " "; } cout<<endl; } void bubble_sort( int array[],...

  • Any help in the compiler error //Driver Program //***************** /** * * CSCI 241 Assignment 8...

    Any help in the compiler error //Driver Program //***************** /** * * CSCI 241 Assignment 8, Part 3 * * Author: your name * z-ID: your z-ID * Date: due date of assignment * * This program builds, sorts and prints lists using the quicksort and * merge sort algorithms. */ #include <iostream> #include <iomanip> #include <vector> #include <string> #include "sorts.h" #include "quicksort.h" #include "mergesort.h" using std::cout; using std::fixed; using std::left; using std::setprecision; using std::string; using std::vector; // Data files...

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
ADVERTISEMENT