44
1 Algorithms and Data Structures: Overview Algorithms and data structures Data Abstraction, Ch. 3 Linked lists, Ch. 4 Recursion, Ch. 5 Stacks, Ch. 6 Queues, Ch. 7 Algorithm Efficiency and Sorting, Ch. 9 Trees, Ch. 10 Tables and Priority Queues, Ch. 11 Advanced Tables, Ch. 12 1-1/2 weeks per chapter (keep up on the reading)

Algorithms and Data Structures: Overvierahimi/cs220/slides/DSChapter3.pdf · 1 Algorithms and Data Structures: Overview Algorithms and data structures Data Abstraction, Ch. 3 Linked

  • Upload
    dinhnhu

  • View
    249

  • Download
    0

Embed Size (px)

Citation preview

1

Algorithms and Data Structures: Overview

Algorithms and data structuresData Abstraction, Ch. 3Linked lists, Ch. 4Recursion, Ch. 5Stacks, Ch. 6Queues, Ch. 7Algorithm Efficiency and Sorting, Ch. 9Trees, Ch. 10Tables and Priority Queues, Ch. 11Advanced Tables, Ch. 12

1-1/2 weeks per chapter (keep up on the reading)

Chapter 3: Data Abstraction

Data Abstraction and Problem Solving with Java: Walls and Mirrors

ByCarrano and Pritchard

3

Modularity

Modularity is:Well-defined components, withWell-defined interfaces

Technique: split each object/procedure into simpler objects/procedures until you have trivial objects/procedures that are easy to design and implement

A technique for managing complexity Design and implementation focuses on one component at a time

Easier to write, read, and modify Isolates errors and eliminates redundancy

4

Modular Design

Interface: What each component does How you communicate with it (inputs and outputs)

Design:How a component does what it does, using other componentsBuild up complex components from simple ones

Top-down design Start with a high-level design, then refine until each component until you get to trivial ones

Bottom-up Implementation Build simple modules and put them together to get complex functionality

5

Data Abstraction

1. Decide what data elements you will be operating on2. Decide what operations you will be doing to each

data element3. Define a clean interface to these operations

That is independent of the implementation

4. Implement the objectsData and data structuresInterfacesProcedures

Now you have an Abstract Data Type (ADT)

6

ADTs vs. Data Structures

An ADT is a description of some type of data (or a collection of data) and the operations on that data

Example: A BankIt stores moneyYou can deposit, withdraw, write checks, check balance

A data structure is a way of structuring some collection of data

Example: A pile of money, a safe full of money, etc.

ADTs have clean interfaces, and the implementation details are hiddenData structures are often used to implement ADTs

7

ADT Examples

Student recordClass ListA Student’s TranscriptA complex numberGraphical elements (e.g., shapes)Formatted documentsA GUI buttonNotice that each of these is a collection of objects

Sometimes the objects in the collection are of the same type, and sometimes different typesBasic objects vs. container objects

Let’s specify these in more detail

8

Example: A List

Think of a list of words:A shopping listA todo listA scheduleA list of people in this classEtc.

In some orderAll of the items are of the same typeOperations: <discuss>Variations: order, type, common operations, size, …

9

ADT List Operations

1. Create an empty list2. Determine whether a list is empty3. Determine the number of items on a list4. Add an item at a given position in a list5. Remove the item at a given position in a list6. Remove all the items from a list7. Get the item at a given position in a list8. Other operations?

10

Specifications: createList()

Description:Creates a new, empty list

Inputs: Nothing or Type of items in list

Outputs:None

Result:A new empty list is created

What haven’t we specified?Size

11

Specifications: isEmpty()

Description:Checks to see if a list is empty

Inputs: None

Outputs: true if the list is emptyfalse if the list is not empty

Result:The list is unchanged

12

Specifications: add(index, item)

Description:Adds an item to a list

Inputs: index: where in the list to add the itemitem: the item to add to the list

Outputs: Throws an exception if the index is out of range, or if the list is fullOtherwise, the list now contains item

Result:If index is valid, item is now in the list and all items after index have moved up one position

13

Specifications: remove(index)

Description:Removes an item from a list

Inputs: index: which item to remove

Outputs: Throws an exception if the index is out of range, or if the list is empty

Result:If index is valid, the item has been removed from the list and all items above index have been moved down one position

14

Specifications: removeAll()

Description:Removes all items from a list

Inputs: None

Outputs: None

Results:The list is now empty

15

Specifications: get(index)

Description:Gets an item from a list

Inputs: index: the item to get

Outputs: Returns the item at the specified indexThrows an exception if index is out of range

Results:The list is unchanged

16

Example Usage

Assume lists contains stringsnew List aList; aList

17

Example Usage

Assume lists contains stringsNew List aList; aList =aList.createList();

18

Example Usage

Assume lists contains stringsNew List aList; aListaList.createList(); MilkaList.add(1, “Milk”);

19

Example Usage

Assume lists contains stringsNew List aList; aListaList.createList(); MilkaList.add(1, “Milk”); EggsaList.add(2, “Eggs”);

20

Example Usage

Assume lists contains stringsNew List aList; aListaList.createList(); MilkaList.add(1, “Milk”); EggsaList.add(2, “Eggs”); ButteraList.add(3, “Butter”);

21

Example Usage

Assume lists contains stringsNew List aList; aListaList.createList(); MilkaList.add(1, “Milk”); EggsaList.add(2, “Eggs”); ButteraList.add(3, “Butter”); AppleaList.add(4, “Apple”);

22

Example Usage

Assume lists contains stringsNew List aList; aListaList.createList(); MilkaList.add(1, “Milk”); EggsaList.add(2, “Eggs”); ButteraList.add(3, “Butter”); AppleaList.add(4, “Apple”); BreadaList.add(5, “Bread”);

23

Example Usage

Assume lists contains stringsNew List aList; aListaList.createList(); MilkaList.add(1, “Milk”); EggsaList.add(2, “Eggs”); ButteraList.add(3, “Butter”); AppleaList.add(4, “Apple”); BreadaList.add(5, “Bread”); ChickenaList.add(6, “Chicken”);

24

Example Usage

Assume lists contains stringsNew List aList; aListaList.createList(); MilkaList.add(1, “Milk”); EggsaList.add(2, “Eggs”); ButteraList.add(3, “Butter”);aList.add(4, “Apple”);aList.add(5, “Bread”);aList.add(6, “Chicken”);aList.add(4, “Nuts”);

AppleBreadChicken

Nuts

25

Example Usage

Assume lists contains stringsNew List aList; aListaList.remove(5); Milk

EggsButterNuts

BreadChicken

Apple

26

ADTs Revisited

ADTS specifyWhat is storedWhat operations can be performed on that dataHow to request the operationsWhat is returnedThe state of the data after the operations

They do not specifyHow the data is stored

Or even that it is stored at allThink of the Bank analogy again

How the operations are performed

27

Our List Operations

add() adds data to a data collectionremove() and removeAll() remove data from a data collectionisEmpty(), size(), and get() ask questions about the data in a data collection

Other operationsdisplayList()replace()List operations or external operations?

28

Using a List: displayList(List aList)

// Display the items in a List// Note: independent of List implementationvoid displayList(List list) {

for(int index = 1; index < aList.size(); index++) {String dataItem = aList.get(index);System.out.println(“item ”

+ index + “: ” + dataItem);}

}

29

Using a List: replace(List a, int i, String item)

// Replace the list element at index i with item// Note: independent of List implementationvoid replace(List a, int i, String item) {

if(i >= 1 && i <= a.size()) {a.remove(i);a.add(i, item);

}}

30

Alternate replace(List a, int i, String item)

// Replace the list element at index i with item// returns true if the operation succeededboolean replace(List a, int i, String item) {

try {a.remove(i);

} catch(ListException e) {return false;

}a.add(i, item);return true;

}

31

Example

See List code

32

Example: A Sorted List

Often data is kept in a specified orderWe call this sorted data

Static lists can be sorted onceDynamic lists (with things being added and deleted) require that either

The modifications maintain the sorted order, orThe data be resorted before certain operations.

Operations: create(), isEmpty(),size(), add(item), remove(index), removeAll(), get(index), find(item).How is this different from a List?

33

Example: A Phone Book

Data:Phone records

Operations:Add an entryRemove an entryLook up someone’s phone number (by name)View all entriesView one entry at a time, in orderGet the number of entries

Details:Stored in alphabetical order

34

Phone Book Data and Operations

1. void add(String firstName, String lastName, String Number);

2. boolean remove(int index);3. int find(String firstName, String lastName);4. String get(index); // returns the number5. int size();

35

Implementing an ADT

Once you have clearly defined data and operation, you can implement your ADTThe implementation must respect the interface that you have definedThe implementation should be flexible

Don’t arbitrarily limit the sizeDon’t make assumptions about how it will be used

The implementation should be efficientFlexibility and efficiency are sometimes at odds

36

Encapsulation

Encapsulation: Placing the data and all of the operations together in one well-defined placeJava supports encapsulation with ClassesClasses define a new data type (an ADT, in fact)Classes contain both the data and the code for the type

Called the member data and member functions (or methods) of that type

37

Public vs. Private

Members (data and methods) can be public or privatePrivate members are accessible only to methods in that class

Private members support data hidingBy default, everything is private

Public members are accessible to any method, inside or outside the class

These are the interface methodsIn general, the member data should always be private, and all data access should be through methods.

38

Member Data vs. Local Variables

Member variables are part of the classThey last as long as the object lastsThey are accessible by any method in the class

Local variables are part of a methodThey last as long as the method is runningThe are accessible only within the method that they are defined in

39

Constructors

Constructors are special methodsThey are called exactly once, when an object is created using newThey initialize member variables, and do anything else necessary at object creationConstructors always have the same name as the classConstructors can take parametersConstructors never return anythingThere can be more than one constructor, with different numbers and/or types of parameters

40

Example

See ListArrayBased code

41

Inheritance

Inheritance creates new classes as subclasses of existing classes

Anywhere the base class would work, but subclass also works (is-a relationship)Example:

Class SortedList extends List {// Adds in sorted orderpublic void add(item) {

<the new add code>}

}

42

Object Equality

Be careful when comparing objects By default every object inherits from Object

Object supports equals()But, equals() tests whether or not two objects are the same objectIf you want to be able to compare two objects, write your own equals() method to replace the equals() method in the Object base class

Your method should compare the data members for equality

43

Java Interfaces

An Interface is a specification of the methods that an object supportsA class may implement an interface

It must support all of the methods in the interface, exactly as they are defined in the interface

A class that implements an interface may be used anywhere that the interface is expected

44

Java Exceptions

Exceptions allow objects to signal exceptional conditions to the objects that called themThey typically indicate run-time errors that are serious, but not fatal

Array index out of bounds, invalid parameter, etc.In C you would return an error codeIn Java you throw an exceptionThe exception must be specified in the definition of the method that may throw itThe calling method must use try and catchSee examples