Title: ITM 172
1ITM 172
- Java Programming
- Chapter 5
- Arrays Part B
2Lab 5.5 CountLettersInArray
- Review only
- This program creates a character array of size
100, and stores 100 random characters in that
array. - Then methods are invoked to count the number of
occurrences of each letter, the average of
times a letter occurs (3) and the standard
deviation of letter occurrences (.38).
3Lab 5.6 TestCopyArray
- Review only
- This program explains that you cant copy the
contents of an entire array simply by assigning
its reference to another array reference
variable. - For example, assume youve declared
- int list1 0, 1, 2, 3, 4, 5
- int list2 new intlist1.length // same
length as list1 - The following statement copies the address in
list1 into list2 so list2 now points to the
same array as list1. Now nobody points to the
array originally referenced by list1.
4Copying the contents of one array into another
- Three ways
- Write a for loop to copy each element of array1
into array2. - Use the static arraycopy method in the System
class. - Use the clone method in the java.lang.Object
class.
5Multi-dimensional Arrays
- A single dimensional array is a row of cells
multi-dimensional arrays are actually grids of
cells with both rows and columns. - To declare a 5 by 5 two-dimensional array whose
reference is named matrix - int matrix new int 5 5
- We will not cover multi-dimensional arrays.
6The Searching Process
- Searching is the process of looking for a
specific element in a data set. - Searching is a common procedure performed by
computers. - For example, every time you call 411 to get
information, a computer program performs a search
through a list of records to locate a specific
name and phone number. - For example, anytime you inquire about your
balance on a credit card or bank account, a
computer program has to perform a search to
locate your specific item of data.
7Searching algorithms
- One area where computer scientists have focused a
lot of research efforts is discovering the
fastest possible way for the computer to search
and retrieve data from large databases (such as a
phonebook). - So far, there are two commonly used methods for
searching - The linear search method
- The binary search method
- The next two examples demonstrate how each search
method works on arrays. The searching processes
discussed could also be performed on databases.
8The Linear Search Method
- A search starts out with a value to search for
(called the key value) which could be a persons
last name, account number, etc. and a list of
values (in this case, the list of values is
stored in an array). - The linear search method looks at each value in
the list/array and compares it to the key. If the
value matches the key, the key value was found
and the search process terminates.
9Lab 5.10 LinearSearch
- This program creates an array of size 10, assigns
10 random values (between 1 and 100) to the 10
array elements. - Then a linear search is performed where the user
enters a value to search for (the key) and the
program determines whether that keys value is in
the array, and if so, it provides the array
position number (called the index ?) where the
key was found.
10(No Transcript)
11(No Transcript)
12(No Transcript)
13Page 209-210
14The Binary Search Method
- If todays computers still used the linear search
method to locate data, it would take 411 about
3-1/2 minutes to locate a name in the NYC phone
book. - Older computers with limited RAM memory size had
only the capability to perform linear searches. - Technological advances in computer design,
allowing computers to use large memory spaces and
virtual memory permit the use of binary search
method. - Todays modern database management systems use
only the binary search process for all searches
except searches performed on very small data sets.
15The Binary Search Process
- 1. Sort the items in the array so they are in
ascending order. - 2. Compare the key value to value that resides in
the middle cell of the array. If a match is
found, the search process terminates. - 3. If the middle value is greater than the key,
go to the middle cell within the upper half of
the array and compare it to the key. If the
middle value is less than the key, go to the
middle cell within the lower half of the array
and compare it to the key.If a match is found,
the search process terminates. - If not chop the list in half again and repeat
step 3.
16The binary search process Step 1
21
Key value
03 07 11 14 16 21 25 26 29 31 34 39
40 43 45 49 54
0 1 2 3 4 5 6 7 8 9 10
1112131415 16
Step 1 Compare the key value (21) to the value
in the (0 16)/2 or 8th position (29). If
its a match, the search process terminates.
17The binary search process Step 2
21
Key value
03 07 11 14 16 21 25 26 29 31 34 39
40 43 45 49 54
0 1 2 3 4 5 6 7 8 9 10
1112131415 16
Step 2 21 is not 29. If (key value lt 29),
eliminate the upper half of the list. Go to the
middle cell of the lower half of the array. If
(key value gt 29), eliminate the lower half of the
list. Go to the middle cell of the upper half of
the array. If its a match, the search process
terminates. Since 21 lt 29, eliminate the upper
half of the list and go to the (0 7)/2
or 3rd position (rounding down).
18The binary search process Step 3
21
Key value
03 07 11 14 16 21 25 26 29 31 34 39
40 43 45 49 54
0 1 2 3 4 5 6 7 8 9 10
1112131415 16
Step 3 21 is not 14. If (key value lt 14),
eliminate the upper half of the (remaining) list.
Go to the middle cell of the lower half of the
array. If (key value gt14), eliminate the lower
half of the (remaining) list. Go to the middle
cell of the upper half of the array. If its a
match, the search process terminates. Since 21 gt
14, eliminate the lower half of the remaining
list and go to the (4 7)/2 or 5th
position (rounding down).
19The binary search process Step 4
21
Key value
03 07 11 14 16 21 25 26 29 31 34 39
40 43 45 49 54
0 1 2 3 4 5 6 7 8 9 10
1112131415 16
Step 4 21 is 21. Therefore, display the index
value where the key was found (position 5) and
terminate the search process.
20Lets try it again.
21The binary search process Step 1
49
Key value
03 07 11 14 16 21 25 26 29 31 34 39
40 43 45 49 54
0 1 2 3 4 5 6 7 8 9 10
1112131415 16
Step 1 Compare the key value (49) to the value
in the (0 16)/2 or 8th position (29). If
its a match, the search process terminates.
22The binary search process Step 2
49
Key value
03 07 11 14 16 21 25 26 29 31 34 39
40 43 45 49 54
0 1 2 3 4 5 6 7 8 9 10
1112131415 16
Step 2 49 is not 29. If (key value lt 29),
eliminate the upper half of the list. Go to the
middle cell of the lower half of the array. If
(key value gt 29), eliminate the lower half of the
list. Go to the middle cell of the upper half of
the array. If its a match, the search process
terminates. Since 49 gt 29, eliminate the lower
half of the list and go to the (9 16)/2
or 12th position (rounding down).
23The binary search process Step 3
49
Key value
03 07 11 14 16 21 25 26 29 31 34 39
40 43 45 49 54
0 1 2 3 4 5 6 7 8 9 10
1112131415 16
Step 3 49 is not 40. If (key value lt 40),
eliminate the upper half of the (remaining) list.
Go to the middle cell of the lower half of the
array. If (key value gt14), eliminate the lower
half of the (remaining) list. Go to the middle
cell of the upper half of the array. If its a
match, the search process terminates. Since 49 gt
40, eliminate the lower half of the remaining
list and go to the (13 16)/2 or 14th
position (rounding down).
24The binary search process Step 4
49
Key value
03 07 11 14 16 21 25 26 29 31 34 39
40 43 45 49 54
0 1 2 3 4 5 6 7 8 9 10
1112131415 16
Step 4 49 is not 45. If (key value lt 40),
eliminate the upper half of the (remaining) list.
Go to the middle cell of the lower half of the
array. If (key value gt14), eliminate the lower
half of the (remaining) list. Go to the middle
cell of the upper half of the array. If its a
match, the search process terminates. Since 49 gt
45, eliminate the lower half of the remaining
list and go to the (15 16)/2 or 15th
position (rounding down).
25The binary search process Step 5
49
Key value
03 07 11 14 16 21 25 26 29 31 34 39
40 43 45 49 54
0 1 2 3 4 5 6 7 8 9 10
1112131415 16
Step 5 49 is 49. Therefore, display the index
value where the key was found (position 15) and
terminate the search process.
26Lab 5.11 Binary Search
- This program demonstrates the binary search
method. - To calculate and re-calculate the midpoint of the
array, the formula (low high)/2 is used. - Initially low 0 and high array length-1
(16 in the previous example), so midpoint is
8. - After the first chop, if it was the upper half
of the list that was eliminated, low remains at
0, but high is recalculated to be midpoint-1
or 7. - If it was the lower half of the list that was
eliminated, low is recalculated to be midpoint1
or 9 and high remains at 16. - When low and high converge, we conclude that the
key value is not contained in the array.
27Page 211-212. Note This program is similar but
not identical to the example in the book. This
example doesnt use recursion.
28(No Transcript)
29(No Transcript)
30(No Transcript)
31Comparing linear to binary search methods
- As the array/list size the grows, the relative
efficiency of the binary search method grows
exponentially. - But dont forget that the binary search process
has more overhead. In other words, the binary
search process only works correctly when the
array/list has been pre-sorted. - Therefore, if the array size is very small, the
linear search method may be more efficient but if
the array size is large, the binary search method
is clearly more efficient.
32key
Array Size
33(No Transcript)
34Sorting Arrays
- Sorting means re-arranging data values so that
they reside in ascending or descending order. - Sorting, like searching, is a very commonly-used
computer application. - In real-world applications, which may involve
sorting thousands or even millions of records in
a database or values in an array, it is very
important that the computer performs the sorting
process as efficiently as possible. - This discussion is not just about sorting
algorithms. Were going to look at two different
algorithms that can sort an array of values and
then well discuss how to choose which algorithm
is better, that is which algorithm is more
efficient.
35An overview of two sorting algorithms
- The selection sort (move max to the end)
- Walk through the array. Find max. Put max in the
last position. Eliminate that position from the
next walk through. Repeat. - Bubble sort (lower values bubble to the
beginning) - Compare two side-by-side numbers. If the one on
the right is smaller, swap. Repeat this process n
times. (where n is the array size).
36Heres the strategy for sorting the numbers using
the selection sort method
- 1. Set n to the index value of last position in
the array (same as length 1 or in this case, 4) - 2. Assume that the last value in the array (the
value in the nth position) is max. - 3. Walk backwards through the array to see if any
other number is gt max. (uses a for loop) - 4. If so, swap the new max with the current max
so that the new max will be in the last position. - 5. Subtract 1 from n so that the last position in
the array is now 1 less (to the left). - 6. Go to step 2. Repeat until the nth position
1.
37Actual method Lab 5.12 SelectionSort( )
- Assume this array has been declared in main( )
- double myList 5.0, 4.4, 1.9, 2.9, 3.4,
3.5 - static void selectionSort ( double list)
-
- The code for this method is on the next slide.
Continued...
38- for (int i list.length-1 i gt1 i--)
-
- currentMax listi // assume the last value
is max - currentMaxIndex i // assume
max is in the last position (i) - for (int ji-1 j gt 0 j--) //
starting with the next-to-last value (j) -
- if (currentMax lt listj) // compare max
to list j -
// if (max lt listj) - currentMax list j // make listj
the new max - currentMaxIndex j // store the position
of new max -
- // repeat this process until j 1
- // swap // After finding max in the array
- if (currentMaxIndex ! I) // if max is not
already last, - // swap max with the last position.
- listcurrentMaxIndex listi
- list i currentMax
-
- // Repeat this whole process ( i - 1 ) times
(iarray size)
39Page 215.
40Here is the strategy for sorting them using the
bubble sort method
- 1. Let A 0 and B 1, n length-1
- 2. Compare the value in A to the value in B.
- 3. If the value in A is larger than the value
in B, then swap their values. - 4. Add 1 to A and 1 to B. Go to step 2. Repeat
until B n - 5. Subtract 1 from n.
- 6. Set A back to 0 and B back to 1. Repeat
steps 1 5 until n1.
41Actual Program BubbleSort.cpp
- Assume that the following array has been declared
in main( ) - double myList 5.0, 4.4, 1.9, 2.9, 3.4,
3.5 - static void bubbleSort (double list)
-
- See next slide
42- static void bubbleSort (double list)
-
- int a, b
- double temp // extra cell used
for 3-step swap - for (int n list.length-1 n gt 0 n--) //
list size gets shorter each time. -
- a0
// compare the values in - for (b1 bltn b, a)
// positions 0 to 1, 1 to 2 - // 2 to 3, then 3
to 4 - if (listb lt lista)
// If value on the left is lt value on right, - // do a swap.
- templistb
- listb lista // The 3-step
swapping procedure - listatemp
-
- // end of inner-loop
- // end of outer-loop
-
43Not in text
44Evaluating Algorithms
- We have two procedures that do exactly the same
thing. - So which one is better?
45That depends how you define better
- Is it the one that uses less memory space?
- Is it the one that completes faster?
46Most people would say, faster
- But how do you measure faster?
- The answer is the one that can complete the
process in the fewest number of steps (CPU
instruction executions / clock cycles).
47How do we determine the number of steps?
- We can add a counter that gets incremented after
each instruction. - We can compare the value of counter for each
algorithm.
48To sort 25 numbers
- It takes bubble sort 1,180 instruction
executions. - It takes selection sort 908 instruction
executions. - So can we conclude that selection sort is better?
Or should we conclude that they are about the
same?
49Before drawing any conclusions.. Consider the
following question
- Suppose someone asked you, if you have to get
from point A to point B, is it faster to run or
drive? - Most of us would say, drive.
- But what if you are going to get the mail out of
the mailbox at the end of the driveway? - Chances are, it would be faster to just run down
the driveway, get the mail, and run back. So the
answer is actually, It depends on how far you
are going.
50The point is
- One algorithm may be faster when the array size
n and slower when array size m. - In order to know which algorithm is better, you
must compare the two for many different values of
n (array size). - The chart on the next slide shows a comparison of
the two algorithms for different list sizes (25,
50, 75, and 100).
51Comparison of sorting methods
52(No Transcript)
53Conclusion
- When the array size is small, the two algorithms
are about the same in terms of efficiency. - But as the array size gets larger and larger, the
relative efficiency of selection sort increases.
For selection sort, the workload increases at a
lower rate as compared to the workload increase
for bubble sort. - The better algorithm is the one whose workload
increases at the lower rate.
54Using Fortes Debugger
- Debugging is the process of finding errors in a
program. - Recall that there are three types of errors that
can be made during program development runtime
errors, syntax/compile time errors, and logical
errors. - The debugger is generally used to locate and
correct the source of logical errors.
55What you can do with the debugger
- Trace through a program or method, watching what
happens as each statement is executed. - You can set variables to watch as the program
executes, set breakpoints (so the program will
run until it gets to that point) and then stop. - You can actually modify variables as the program
is running to see what happens when a variables
value is different.
56Well use the SelectionSort program to test the
debugger
- Lets the run the debugger first on a program
that does not have any errors.
57To start the debugger
- Make sure that your cursor is positioned in the
source code window displaying the SelectionSort
program. - To start the debugger in step-into mode, from
the pull-down menu, select - Debug, Step into
58The next line to be executed shows in green.
Program execution pauses a the first line in the
main( ) method.
59The debugger window
Click these buttons to add or remove panes.
This is the watches pane. We can add variables
to the watches pane so we can see how the value
in this variable changes as the program executes.
60To add the myList array to the watches
pane 1.Position the cursor on the (green) line
of code where myList is declared in the source
editor window. 2. Right click with the mouse. 3.
Select Add Watch
614. Type or see the variable name myList. 5.
Click ok. 6. See the variable name appear in
the watch window. Since that line of code has not
be executed yet, myList doesnt exist yet so you
see the message identifier cannot be resolved.
62To step through the program, executing one line
of code at a time, from the pull-down menu,
select Debug, Step Over OR press the F7 key.
63Proceed through the program, one line at a time
by pressing the F7 (step into) key. Lines of code
that contain calls to pre-defined methods such as
println should be stepped over (use F8). The
current execution point (shown in green in the
source editor window) is now on the next line of
code. As the program proceeds, you can see the
array elements and their values changing in the
watches pane.
64Debugging the selectionSort( ) method
- Lets use the debugger to walk through just the
selectionSort( ) method so we can see how the
values in the array are being re-arranged as the
sorting process proceeds. - 1. First, well start the debugger.
- 2. Next, we will set a breakpoint where the
selectionSort( ) method is called. - 3. Next, we will set a watch on each variable
declared in method selectionSort( ). - 4. Next, well step through the selectionSort( )
method using the F7 key.
65- To start the debugger, position your cursor in
the source editor window of the SelectionSort
program. - From the pull-down menu, select Debug, Start
- 3. See the debugger window and the output windows
open.
66To set a breakpoint at the place where method
SelectionSort( ) is called 1. Position the
cursor on the line of code that contains the
method call. 2. Right click, and select Toggle
breakpoint. 3. See the breakpoint appear as an
item in the breakpoint pane.
67- For each of the three variables to be watched
(currentMax, currentIndex, list (array) - Position your cursor on the line of code where
the variable is declared (ex currentMax). - Right click with the mouse.
- Select Add Watch.
684. See the variables name in the Add Watch
window. 5. Click Ok.
696. See the variable listed as a watch in the
watches pane.
70Set the variables currentMaxIndex and list
(array) as watches using the same procedure.
71Start the debugger. It automatically will run to
the breakpoint From the pull-down menu, select
Debug, Start.
72When the cursor stops on the breakpoint, press F7
to start stepping through the program. To view
the list arrays values, click in the watches
pane and expand the list variable by clicking the
symbol next to the eye.
73Now, click back in the source code window and
continually press F7 to step through the
selectionSort( ) methods code. When the method
completes, program control returns to method
main( ). You can continue to step through main( )
by pressing F7 but press F8 to step over lines
of code that contain calls to external methods
such as print( ) or println( ).
74(No Transcript)