Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Programming: Guided Learning with Early Objects Chapter 8 Applications of Arrays (Sorting and Searching) and Strings.

Similar presentations


Presentation on theme: "Java Programming: Guided Learning with Early Objects Chapter 8 Applications of Arrays (Sorting and Searching) and Strings."— Presentation transcript:

1 Java Programming: Guided Learning with Early Objects Chapter 8 Applications of Arrays (Sorting and Searching) and Strings

2 Java Programming: Guided Learning with Early Objects2 Objectives Explore how to sort an array using the selection sort algorithm Explore how to sort an array using the insertion sort algorithm Learn how to implement the sequential search algorithm Learn how to implement the binary search algorithm

3 Java Programming: Guided Learning with Early Objects3 Objectives (continued) Learn how to avoid bugs by developing test suites in advance Become acquainted with the class Vector Learn more about manipulating strings using the class String Learn how to use the layout managers FlowLayout and BorderLayout

4 Java Programming: Guided Learning with Early Objects4 Objectives (continued) Explore how to create menus in a GUI program Learn how to write applets

5 Java Programming: Guided Learning with Early Objects5 List Processing List: a set of values of the same type Basic operations performed on lists: –Search the list for a given item –Sort the list –Insert an item into the list –Delete an item from the list Implement the algorithms Place the methods in class SortSearchAlg

6 Java Programming: Guided Learning with Early Objects6 Selection Sort Selection sort: –Selecting one element –Move the element to its proper place in the list Find the smallest element in unsorted portion of the list Move it to the top of the unsorted portion of the list First time: search entire list for smallest item Second time: locate smallest item in list starting from second element

7 Java Programming: Guided Learning with Early Objects7 Figure 8-1 List of 10 elements Figure 8-2 Smallest element of unsorted list

8 Java Programming: Guided Learning with Early Objects8 Figure 8-3 Swap elements list[0] and list[7] Figure 8-4 List after swapping list[0] and list[7]

9 Java Programming: Guided Learning with Early Objects9 Figure 8-5 Smallest element in unsorted portion of list Figure 8-6 Swap list[1] and list[3]

10 Java Programming: Guided Learning with Early Objects10 Figure 8-7 list after swapping list[1] and list[3]

11 Java Programming: Guided Learning with Early Objects11 Selection Sort (continued) List of length n –On average: n(n-1)/2 key comparisons –3(n-1) item assignments Example: n = 1000 –500,000 key comparisons –3000 item assignments

12 Java Programming: Guided Learning with Early Objects12 Insertion Sort Reduces key comparisons Increases item assignments Inserts each element in its proper place Figure 8-8 list

13 Java Programming: Guided Learning with Early Objects13 Figure 8-9 Sorted and unsorted portion of list Figure 8-10 Move list[4] into list[2]

14 Java Programming: Guided Learning with Early Objects14 Figure 8-11 Copy list[4] into temp Figure 8-12 List before copying list[3] into list[4] and then list[2] into list[3]

15 Java Programming: Guided Learning with Early Objects15 Figure 8-14 List after copying temp into list[2] Figure 8-13 List after copying list[3] into list[4] and then list[2] into list[3]

16 Java Programming: Guided Learning with Early Objects16 Insertion Sort During sorting phase, array divided into upper sublist and lower sublist For list of length n –On average (n 2 + 3n – 4)/4 key comparisons –n(n – 1)/4 item assignments Example: n = 1000 –250,000 key comparisons –250,000 item assignments

17 Java Programming: Guided Learning with Early Objects17 Sequential Search Preconditions: –List, usually an array –Length of the list –Value of item sought Postconditions: –If item found, report success –If item not found, failure reported Sequential search searches an array sequentially starting from first element

18 If search item is second item, sequential search makes two key comparisons If item not in list, makes 1000 key comparisons On average, if list 1000 makes 500 comparisons Java Programming: Guided Learning with Early Objects18 Figure 8-23 List of 1000 elements Sequential Search (continued)

19 Java Programming: Guided Learning with Early Objects19 Binary Search Operates on sorted list –Much faster than sequential list Divide and conquer –Search item compared to middle item –If less than middle item, search lower list –If greater than middle item, search upper list Figure 8-24 List of length 12

20 Java Programming: Guided Learning with Early Objects20 Figure 8-25 Search list, list[0]…list[11] Figure 8-26 Search list, list[6]…list[11]

21 Java Programming: Guided Learning with Early Objects21 Performance of Binary Search Every loop iteration reduces list by half Every iteration makes two key comparisons Example: –List of size 1,000,000 = 2 20 –Loop will have at most 21 iterations –Every iteration has 2 comparisons –At most, 42 comparisons In general, sorted list of size n, –At most, 2log 2 n+2 comparisons

22 Java Programming: Guided Learning with Early Objects22 Figure 8-28 List L Figure 8-29 Search list

23 Java Programming: Guided Learning with Early Objects23 Figure 8-30 Search list after first iteration Figure 8-31 Search list after second iteration

24 Java Programming: Guided Learning with Early Objects24 Designing a Class to Process int Arrays (Revisited, Optional) Design searching and sorting algorithms for array-based lists Enhance capability of class ArrayListClass –Add algorithms to the class with slight modification

25 Java Programming: Guided Learning with Early Objects25 Avoiding Bugs: Developing Test Suites in Advance Correct result for one input may be incorrect for different input Develop efficient test suite to test every kind of input –Special attention to boundary values Test suite is a collection of input values –Often with corresponding expected output –Determined in advance –Verifies program written correctly

26 Java Programming: Guided Learning with Early Objects26 Avoiding Bugs: Developing Test Suites in Advance (continued) Test binary search with a list of: –No elements –One element (search item) –One element Search item smaller or larger than the element –MAXINT elements Search item in first position, last position, middle –MAXINT elements not containing search item –Even number of elements containing search item

27 Java Programming: Guided Learning with Early Objects27 Avoiding Bugs: Developing Test Suites in Advance (continued) Test binary search with list of (continued): –Even number of elements Search item in first, last, and intermediate position Search item smaller than smallest, larger than largest, or neither –Odd number of elements Search item in first, last, and intermediate position Search item smaller than smallest, larger than largest, or neither

28 Java Programming: Guided Learning with Early Objects28 class Vector Limitations of arrays: –Size is fixed Initial estimate may result in array that is too large or too small –Inserting element requires array be shifted –Removing element requires array be shifted class Vector implements a list –Can grow and shrink during program execution Cost in execution time

29 Java Programming: Guided Learning with Early Objects29 class Vector (continued) Every element of a Vector is a reference variable Add element to a vector: –Create the appropriate object –Store data into the object –Store address of object into Vector element Syntax: Vector stringList = new Vector ();

30 Java Programming: Guided Learning with Early Objects30 Figure 8-32 stringList after adding four strings

31 Java Programming: Guided Learning with Early Objects31 Primitive Data Types and the class Vector Every element of a Vector is a reference Primitives must be wrapped in an object –Java provides wrapper class for each primitive –Use autoboxing and auto-unboxing Example: Vector list = new Vector (); list.addElement(13); list.addElement(new Integer(13));

32 Java Programming: Guided Learning with Early Objects32 Vector Objects and the foreach Loop The foreach loop processes elements of a collection object one at a time The foreach can be used on Vector object Syntax: for (type identifier: vectorObject) statements –identifier is a reference variable –Data type is same data type as objects stored in vectorObject

33 Java Programming: Guided Learning with Early Objects33 Abstract Data Types (Optional) List is an example of an abstract data type (ADT) ADT is an abstraction of a commonly appearing data structure, together with a set of operations Provides data hiding –Implementation details of operations and data hidden from users of the ADT

34 Java Programming: Guided Learning with Early Objects34 class String (Revisited) class String discussed in Chapter 3 Methods of class String : –substring –length –charAt –indexOf Other methods: –startsWith –endsWith –regionMatches

35 Java Programming: Guided Learning with Early Objects35 Table 8-3 Effect of Some String Methods

36 Java Programming: Guided Learning with Early Objects36 GUI Layout Managers, Menus, and Applets (Optional) GUI components: –Layout managers –Creating menus –Applets

37 Java Programming: Guided Learning with Early Objects37 Layout Managers Two layout managers discussed in earlier chapters: –Grid Layout –null GridLayout : –Specify number of rows and columns –Place components left to right, row-by-row, top to bottom null layout: –Specify size and location

38 Java Programming: Guided Learning with Early Objects38 FlowLayout Default layout manager for Java applications Places components left to right and centered until no more items can be placed on first line Next items placed on second line Not guaranteed to have same number in each row Align left, right, or center –Default is centered

39 Java Programming: Guided Learning with Early Objects39 Figure 8-40 Sample run of the FlowLayoutExample program

40 Java Programming: Guided Learning with Early Objects40 BorderLayout Place items in specific regions Divides container into five regions: –NORTH and SOUTH extend horizontally –EAST and WEST extend vertically between components NORTH and SOUTH –CENTER expands to occupy unused regions

41 Java Programming: Guided Learning with Early Objects41 Figure 8-41 Sample run of the BorderLayoutExample program

42 Java Programming: Guided Learning with Early Objects42 Menus Provide functionality without clutter Attached to objects such as JFrame and JApplet Method setJMenuBar creates a menu bar –Menus displayed in menu bar in order added Inner class handles action event

43 Java Programming: Guided Learning with Early Objects43 Figure 8-42 Sample run of the TextEditor program

44 Java Programming: Guided Learning with Early Objects44 Applets Java program embedded within an HTML document –Executed by a Web browser Extend class JApplet contained in package javax.swing Does not contain a main method –Methods init, start, paint overridden Method paint takes Graphics object as argument

45 Java Programming: Guided Learning with Early Objects45 Figure 8-43 Output of the WelcomeApplet

46 Java Programming: Guided Learning with Early Objects46 Applets (continued) Method init : –Initializes variables –Gets data from the user –Places GUI components Method paint : –Creates output Method drawString from class Graphics displays text Compile and embed.class file in HTML

47 Java Programming: Guided Learning with Early Objects47 Summary Selection sort finds smallest element in unsorted portion –Moves it to top of unsorted portion For list of length n, makes n(n-1)/2 comparisons –Makes 3(n-1) assignments Insertion sort inserts elements in its place For list of length n, makes (n 2 + 3n – 4)/4 comparisons –Makes n(n-1)/4 assignments

48 Java Programming: Guided Learning with Early Objects48 Summary (continued) Sequential search searches for item starting at first position until item found or list exhausted –On average, searches half the list Binary search takes a divide and conquer approach –Much faster than sequential search class Vector implements a list –Can grow and shrink during program execution

49 Java Programming: Guided Learning with Early Objects49 Summary (continued) FlowLayout manager places GUI components left to right BorderLayout manager component placed at center expands to occupy unused space Menus provide functionality and reduce clutter Applet is a program embedded in HTML and viewed by a Web browser

50 Java Programming: Guided Learning with Early Objects50 Summary (continued) Create an applet by extending class JApplet Java applet does not have a method main Methods init, start, paint guaranteed to be invoked in sequence Statements executed once kept in init method Applet does not have a title


Download ppt "Java Programming: Guided Learning with Early Objects Chapter 8 Applications of Arrays (Sorting and Searching) and Strings."

Similar presentations


Ads by Google