In: Computer Science
c++ question:
int ArrayList::binarySearchID(string firstN) const
{
int first = 0;
int last = length - 1;
int mid = (first + last) / 2;
bool found = false;
int index;
while (!found && last >= first)
{
if (firstN == list[mid])
{
found =
true;
}
else if (firstN >
list[mid])
{
first = mid -
1;
}
else if (firstN <
list[mid])
{
last = mid -
1;
mid = (first +
last) / 2;
}
}
if (found) {
cout << "Index" <<
list[index] << " in array list." << endl;
return mid;
}
else
{
return -1;
}
}
Q: since firstN is a string it can't compare to an ArrayList * list so how am i suppose to write these parts comparing the string to the list[mid]?
"if (firstN == list[mid])"
Q:How am i suppose to print the index?
( cout << "Index" << list[index] << " in array list." << endl; )
int ArrayList::binarySearchID(string firstN) const { int first = 0; int last = length - 1; int mid = (first + last) / 2; bool found = false; int index; while (!found && last >= first) { if (firstN == list[mid]) { found = true; index = mid; } else if (firstN > list[mid]) { first = mid - 1; } else if (firstN < list[mid]) { last = mid - 1; mid = (first + last) / 2; } } if (found) { cout << list[index] << " is found on index " << index << " in array list." << endl; return index; } else { return -1; } }
Since you have not shared the code for arraylist class, i am not
sure how you are storing your objects/elements in arraylist..
Ideally for an arraylist, you will be having an array of string,
inside which you must be putting your elements..
Then using that array if you say arr[i], then it will give you
string value on index i.. I am assuming you have array with name
list in class, hence when you say list[mid], it gives you the
string value stored on index mid in the array..