Dale - Computer Science Illuminated 314

# Dale - Computer Science Illuminated 314 - binary search...

This preview shows page 1. Sign up to view the full content.

9.4 Sorting 287 Additional List Operations What other operations do we do on our “to-do” list? Do you ever look to see if an item is on the list in order to add an item if it isn’t? Do you ever look to see if the list is empty? Is full? These operations are called observer operations because they observe the state of the list. Let’s examine the algorithm to determine if an item is in the list. This method should be a Boolean method. We have to start at the beginning of the list and compare each item in the list to the one passed as a parameter. Once we find a match we return true . If we reach the end of the list without having found a match, we return false . This algorithm is called a sequential search for obvious reasons. We begin at the first item and examine them in order. You are asked to complete the algorithms for the other observer operations in the exercises at the end of this chapter. In the next sections we examine algorithms that transform an unsorted list into a sorted one. Then we look at the
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: binary search algorithm, a faster searching algorithm that we can use if we know the list is sorted and the implementation is array based. 9.4 Sorting We all know what sorting is. We sort our sock drawers, our bookshelves, even our priorities. Sorting is putting things in order. In computing, trans-forming an unsorted list into a sorted list is a common and useful opera-tion. Whole books have been written about various sorting algorithms, as well as algorithms for searching a sorted list to find a particular element. The goal is to come up with better, more efficient, sorts. Because sorting a large number of elements can be extremely time-consuming, a good sorting algorithm is very desirable. This is one area in which programmers are sometimes encouraged to sacrifice clarity in favor of speed of execution. IsThere(item) Set tempItem to the first item While ( more items ) If (tempItem.compareTo(item) is equal to 0) return true Else Set tempItem to next item Return false...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online