How will this function help sort a struct array of characters?
Well out teacher told us to modify, this function to sort string names inside an array structure.
Here is what he posted in the assigment.
"The words are to be stored in a statically-declared array. You can assume that the maximum number of
unique words that will be submitted is 200. The words are to be stored in the array in sorted order, and you
are to use the array-based binary search method as described in our course notes to locate words in the array."
Code:
int binarySearch (int sortedArray[], int first, int last, int key) {
// Searches sortedArray[first]..sortedArray[last] for key.
// returns: index of the matching element if it finds key,
// otherwise -(index where it could be inserted)-1.
// parameters:
// sortedArray in array of sorted (ascending) values.
// first, last in lower and upper subscript bounds
// key in value to search for.
// returns:
// index of key, or -insertion_position -1 if key is not
// in the array. This value can easily be
// transformed into the position to insert it.
while (first <= last) {
int mid = (first + last) / 2; // compute mid point.
if (key > sortedArray[mid])
first = mid + 1; // repeat search in top half.
else if (key < sortedArray[mid])
last = mid - 1; // repeat search in bottom half.
else
return mid; // found it. return position
}
return -(first + 1); // failed to find key
} // end binarySearch
Will this really worked? because as far as I can understand it it only returns the location of the value, but it just doesn't sort a thing.
I plan to declare my structure like this
Code:
Struct Words{
string word;
int line;
}word[100];
one hundred is the number of words and line keeps track of where the word was found.