# Thread: understanding searching and sorting

1. ## understanding searching and sorting

In the function definition of a binary search algorithm, what's the purpose of first <= last in this line of code?
Code:
`while (!found && first <= last)`
Also, why does one have to be subtracted from the number of elements in the for loop in a linear search algorithm?
Code:
`for (int i = 0; i < number_of_elements - 1; i++)`

2. 1st) If First (which is changed everytime time you go throught the search), is larger than the last element of the array, then obviously the key doesn't exist in there...If the first is smaller than the last, then there is still a possibility that the key your looking for is somewhere there, so thats why it has that condition

2nd) i think that tidbit of code is wrong....I haven't used the linear search in a while, but if I remember correctly it's either i < number_elements, or i <= number_elements .....

3. I meant bubble sort instead of linear search.

4. with the bubble sort, the last 2 items in the array are swapped, so the 2nd to last, and last are swapped, and if you had the for loop setup with the last, and not hte last - 1, it would swap the last with the last + 1, which is obviously non existent causing some serious problems.