Searching Algorithms

Linear/Sequential Search
A linear/sequential search algorithm looks at each element in the array until it finds what it's looking for. This is easy to do with a for loop.

Binary Search
A binary search algorithm only works for a sorted array of elements. The first element is "min", the last element is "max", and the element right in the middle is "mid". If the element you're searching for is above "mid", then mid+1 becomes the new "min". Or, if the element you're searching for is lower than mid, then mid-1 becomes the new "max". This continues until the value of the element you're searching for becomes mid, and the position of mid is returned. Or, if the element doesn't exist in the array, "min" becomes higher than "max", and -1 is returned.

Binary search is a lot more efficient than linear search, because the algorithm is able to continuously cut out half the elements in the array.

No comments:

Post a Comment