#Iterative and Binary Search Help

6 messages · Page 1 of 1 (latest)

primal dune
#

Currently in an intro to C++ class and need some help with my iterative search and binary search code.

# include <iostream>
# include <vector>
# include <fstream>
# include <ctime>
using namespace std;

int iterativeSearch(vector<int>v, int elem){
    for (int i = 0; i < v.size(); i++){
        if (v[i] == elem){
            return i;
        }
    }

    return -1;
}

int binarySearch(vector<int> & v, int startIndex, int endIndex, int elem){
    if (startIndex > endIndex){
        return -1;
    }

    int mid = (startIndex + endIndex) / 2;

    if (v[mid] > elem) {
        endIndex = mid - 1;
    }

    else if (v[mid] < elem) {
        startIndex = mid + 1;
    }

    else {
        return mid;
    }

    return binarySearch(v, startIndex, endIndex, elem);
}

void vecGen(string filename, vector<int> & v){
    ifstream file(filename);
    int num;
    v.clear();
    while (file.is_open() && file >> num){
        v.push_back(num);
    }
    file.close();
}

int main(){
    vector<int> v;
    vecGen("1000_numbers.csv", v);

    vector<int> elem_to_find;
    vecGen("test_elem.csv", elem_to_find);

    for(int i = 0; i < elem_to_find.size(); i++){
        int elem = elem_to_find[i];

        clock_t start = clock();
        int index_if_found = iterativeSearch(v, elem);
        clock_t end = clock();

        double elapsed_time_in_sec = (double(end-start)/CLOCKS_PER_SEC);

        cout << index_if_found << ":" << elapsed_time_in_sec << endl;
    }

    for(int i = 0; i < elem_to_find.size(); i++){
        int elem = elem_to_find[i];

        clock_t start = clock();
        int index_if_found = binarySearch(v, 0, v.size()-1, elem);
        clock_t end = clock();

        double elapsed_time_in_sec = (double(end-start)/CLOCKS_PER_SEC);

        cout << index_if_found << ":" << elapsed_time_in_sec << endl;
    }
}

Here is the code I wrote. vecGen and the iterativeSearch loop in main was provided for me.

barren emberBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

primal dune
#

34483
97151
2584565
3606506
11607937
11178866
82510483
99645501
96798692
99995321

#

The output its giving me is: -1:0
-1:0
-1:0
-1:0
-1:0
-1:0
-1:0
-1:0
-1:0
-1:0
-1:0
-1:0
-1:0
-1:0
-1:0
-1:0
-1:0
-1:0
-1:0
-1:0

#

What exactly is wrong?