SLIDE 2 2 Solutions to Chapter 10 Exercises 10.2. We assumed all elements in an array are distinct, that is, there are no du-
plicate values in the array. What will be an effect to the linear search algo- rithm if an array contains duplicate values? If the array contains duplicate values, then the linear search will return the value that is stored in the first position, i.e., the smallest index. A new search routine must written to return the positions for all duplicate val- ues.
10.3. Will the sorting algorithms presented in this chapter work if the unsorted
array contains any duplicate values? Yes, duplicate values will not cause any problem.
10.4. In this chapter we analyzed sorting algorithms by counting the number of
- comparisons. Another possible method for analyzing the algorithms is
counting the number of data exchanges. How many data exchanges do the selection and bubble sort make in the worst case? Regardless of the origi- nal list, the selection sort will make the same number of data exchanges. However, the number of data exchanges the bubble sort makes depends
- n the arrangement of elements in the original list.
In the case of selection sort, the total number of data exchanges is N-1, the same number as the number of passes because selection sort performs
- ne data exchange after every pass.
In the case of bubble sort, the total number of data exchanges in the worst case is equal to the total number of comparisons. In other words, in the worst case, every comparison will result in a data exchange. This situa- tion happens when the original array is the reverse order (i.e., sorted in descending order). We already know the total number of comparisons (== the total number of data exchanges) in the worst case is
10.5. Another simple sorting algorithm is called an insertion sort. Suppose we
have a sorted list of N elements and we need to insert a new element X into this list to create a sorted list of N+1 elements. We can insert X at the
N 2 – ( ) N 1 – ( ) … 1 + + + i
i 1 = N 2 –
∑
N 2 – ( ) N 1 – ( ) 2
≅ = =