Searching and sorting algorithms - OCRLinear search
Sorting and searching are two of the most frequently needed algorithms in program design. Standard algorithms have evolved to take account of this need.
A linear search is the simplest method of searching a dataUnits of information. In computing there can be different data types, including integers, characters and Boolean. Data is often acted on by instructions. set.
Starting at the beginning of the data set, each item of data is examined until a match is made. Once the item is found, the search ends.
A way to describe a linear search would be:
Find out the length of the data set.
Set counter to 0.
Examine value held in the list at the counter position.
Check to see if the value at that position matches the value searched for.
If it matches, the value is found. End the search.
If not, increment the counter by 1 and go back to step 3 until there are no more items to search.
Consider this list of unordered numbers:
Suppose we were to search for the value 2. The search would start at position 0 and check the value held there, in this case 3.
3 does not match 2, so we move on to the next position.
The value at position 1 is 5.
5 does not match 2, so we move on to the next position.
The value at position 2 is 2 - a match. The search ends.
A linear search in pseudocode might look like this:
find = 2
found = Falselength = list.length
counter = 0
while found == False and counter < length
if list[counter] == find then
found = True
print ('Found at position', counter)
else:
counter = counter + 1
endif
endwhile
if found == False then
print('Item not found')
endif
A linear search, although simple, can be quite inefficient. Suppose the data set contained 100 items of data, and the item searched for happens to be the last item in the set? All of the previous 99 items would have to be searched through first.
However, linear searches have the advantage that they will work on any data set, whether it is ordered or unordered.