Briefly explain this to me

So in my intro to c++ class, we've started searching and sort algorithms;mainly linear search, binary search, bubble sort and selection sort. For the most part, I the understand their structure. What I want to make sure that I understand is why does every example include subtract -1 from the position of the search value? My guess is too avoid the off-by-one error. The same when it comes to arrays and vectors. I would greatly appreciate it if someone would shed some light on this for me.
Not sure I understand what you mean. Note that array indices start at 0.
Let me include an example of some pseudo-code for a linear search program.

Set found to false.
Set position to -1 .
Set index to 0
While found i s false and index < number of elements
It list[index] is equal to search value
found = true .
position = index.
End If
Add 1 to index.
End While.
Return position .

Like I said in my previous post, it's probably subtracting 1 from position because if you don't you'll be off by one(the off-by-one error) in an array. I just want someone to reassure me that what I'm saying is true.
You mean
Set position to -1 .
?
That's not subtraction. The position variable is initialized to -1 so that if the value is not found the function will return -1.
oops, yes you're correct. Thanks for your reply.
Last edited on
btw, I always read your name as Death's lice.
Topic archived. No new replies allowed.