"Write a program that has an array of at least 20 integers. It should call a function that uses the linear search algoritm to locate one of the values. The function should keep a count of the number of comparisons it makes until it finds the value. The program then should call a function that uses the binary search algorithm to locate the same value. It should also keep count of the number of comparisons it makes. Display these values on the screen."

My teacher has requested to use a text file for the integers that has 20,000 of them.

How can I call the text file? It's been to long and I can't find it in the book? I also can't find where it shows how to get the function to cout the number of times it has to search until it finds the value. Haven't tried the binary search yet, can't get past this part.

Thanks!

#include <iostream>
using namespace std;

// Function prototype
int searchList(int[], int, int);

const int SIZE = 20000;  //???

int main()

{

    int bench[SIZE] = { 


    };


int results;


}

int searchList(int list[], int numElems, int value)
{
int index = 0; // Used as a subscript to search array
int position = -1;  // To record position of search value
bool found = false;  // Flag to indicate if the value is found

while (index < numElems && !found)
{

    if (list[index] == value)  // If the value is found
{
        found = true;  // Set the flag
        position = index;  / Record the value's subscript
    }
    index++;  // Go to the next element
}
return position;  // Return the position, or -1
}

Recommended Answers

All 4 Replies

Use ifstream to open and read the integers from a text file into an array. Your program should have a loop that will read a single integer and insert it into the next available index of the array. I'm sure your text book has examples of how to do something like that.

Something like this?

I'm still confused

add #include <fstream>


ifstream in("C:/path/to/text/file.txt");
int counter = 0;
while (in.good() && counter <= SIZE)
{
bench[counter] = (int)in.getLine(); //assuming each line stores one number
counter++;
}
in.close()

close. After this loop finished, counter will contain the number of elements read, so you should use that variable instead of SIZE when searching the array.

add #include <fstream>


ifstream in("C:/path/to/text/file.txt");
int counter = 0;
while (counter < SIZE && in >> bench[counter] )
{
    counter++;
}
in.close()

xexex,
please copy and paste whole program's source code so i can better assist you. also, i'm curious how you did it.

thanks,
flexeblesteel

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.