40
Data Structures and Algorithms - Chapter 3 Abstract Data Types Mohamed Mustaq

Data Structures and Algorithms -- Chapter 3 Abstract Data Types Mohamed Mustaq

Embed Size (px)

Citation preview

Data Structures and Algorithms

--

Chapter 3

Abstract Data Types

Mohamed Mustaq

Prof A Alkhorabi 3- 2

• Data types: values, operations, and data representation (in memory).

• Abstract data type: values and operations only.• Requirements, contract, implementation(s).• Design of abstract data types.• String abstract data types.• Abstract data types in the C++ class library.

Abstract Data TypesOverview

Prof A Alkhorabi 3- 3

Data types

• We classify all data into data types, such as:

– Floating-point numbers

– integers

– objects of various classes.

• Each data type is characterized by:

– a set of values

– a data representation(which is common to all these values)

– a set of operations(which can be applied uniformly to all these values).

Prof A Alkhorabi 3- 4

C++ built-in data types

Type24 Values Data representation

Operations

bool false, true 1 byte || && !

char Unicode characters 2 bytes (as for int)

int negative, zero, positive whole numbers

4 bytes + - * / %< > == etc.

float negative, zero, positive floating-point numbers

4 bytes floating-point

+ - * /

double negative, zero, positive floating-point numbers

8 bytes floating-point

+ - * /

Prof A Alkhorabi 3- 5

Introducing new data types

• To introduce a new data type, we must define its values, data representation, and operations.

• In C++, use a class declaration:

– The class’s instance variables determine the values and data representation.

– The class’s constructors and methods are the operations.

• Each object of the class:

– has those instance variables

– is created by one of those constructors

– may be inspected and/or updated by any of those methods.

Prof A Alkhorabi 3- 6

Abstract data types

• An abstract data type (ADT) is characterized by:

– a set of values

– a set of operations.

It is not characterized by its data representation.

• The data representation is private, so application code cannot access it. (Only the operations can.)

• The data representation is changeable, with no effect on application code. (Only the operations must be recoded.)

Prof A Alkhorabi 3- 7

ADT specification

• Each ADT should have a contract that:– specifies the set of values of the ADT– specifies each operation of the ADT

(i.e., the operation’s name, parameter type(s), result type, and observable behavior).

• The contract does not specify: – the data representation, nor

– the algorithms used to implement the operations.

Prof A Alkhorabi 3- 8

ADT specification

• The ADT programmer undertakes to provide an implementation of the ADT

• The application programmer undertakes to process values of the ADT using only the operations specified

• Separation of concerns:– The ADT programmer is not concerned with

what applications the ADT is used for.– The application programmer is not concerned

with how the ADT is implemented.• Separation of concerns is essential for designing

and implementing large systems.

Prof A Alkhorabi 3- 9

Example: Contract for Date ADT

• Assumed application requirements:1) The values must be all past, present, and future dates.

2) It must be possible to construct a date from year number y, month number m, and day-in-month number d.

3) It must be possible to compare dates.

4) It must be possible to put a date in ISO format “y-m-d”.

5) It must be possible to advance a date by n days.

Prof A Alkhorabi 3- 10

Example: Specifications for Date ADT

• Possible specifications (contract), expressed as an outline class declaration:

class Date {// Each Date value is a past, present, or future date.

private …;public Date (int y, int m, int d);// Construct a date with year y, month m, and day-in-month d.

public int compareTo (Date that);// Return –1 if this date is earlier than that, // or 0 if this date is equal to that, // or +1 if this date is later than that.

Prof A Alkhorabi 3- 11

Example: Specifications for Date ADT

public String toString ();// Return this date rendered in ISO format.

public void advance (int n);// Advance this date by n days (where n ≥ 0).

}

Prof A Alkhorabi 3- 12

Example: Specifications for Date ADT

• Possible application code:Date today = …;Date DOB = new Date(2001, 4, 15);today.advance(16);if (today.compareTo(DOB) < 0)

cout << today.toString();

Prof A Alkhorabi 3- 13

ADT implementation

• An implementation of an ADT entails:– choosing a data representation– choosing an algorithm for each operation.

• The data representation must be private.

• The data representation must cover all possible values.

• The operations algorithms must be consistent with the data representation.

2جواب

Prof A Alkhorabi 3- 14

Example: implementation of Date ADT

• Class declaration:

class Date {// Each Date value is a past, present, or future date.

// This date is represented by a year number year, a month number

// month, and a day-in-month number day:private: int year, month, day;

public: Date (int y, int m, int d) {// Construct a date with year y, month m, and day-in-month d.

year = y; month = m; day = d;}

Prof A Alkhorabi 3- 15

Example: implementation of Date ADT

• Class declaration (continued):

int compareTo (Date that) {// Return –1 if this date is earlier than that, // or 0 if this date is equal to that, // or +1 if this date is later than that.

return (year < that.year ? -1 : year > that.year ? +1 :

month < that.month ? -1 : month > that.month ? +1 : day < that.day ? -1 : day > that.day ? +1 : 0);

}

Prof A Alkhorabi 3- 16

Example: implementation of Date ADT

• Class declaration (continued):String toString () {// Return this date in ISO format.

return newFormatDate;// year + '-' + month + '-‘ + day

}void advance (int n) {// Advance this date by n days (where n ≥ 0).

…}

}

Prof A Alkhorabi 3- 17

ADT design

• Operations are sufficient if together they meet all the ADT’s requirements.

– Can the application be written entirely in terms of calls to these operations?

• An operation is necessary if it is not surplus to the ADT’s requirements.

– Could the operation be safely omitted?

• A well-designed ADT provides operations that are necessary and sufficient for its requirements.

Prof A Alkhorabi 3- 18

Example: design of Date ADT

• Recall the Date specification :class Date {

private: …;public: Date (int y, int m, int d);

int compareTo (Date that);String toString ();void advance (int n);

}• These operations are sufficient.• All these operations are necessary.

Prof A Alkhorabi 3- 19

Example: design of Date ADT

• Consider another possible Date specification:

public class Date {private: …;public: Date (int y, int m, int d);

int getYear ();int getMonth ();int getDay ();

}• These operations are sufficient. (Date comparison and

rendering are clumsier, but still possible.)

• All these operations are necessary.

Prof A Alkhorabi 3- 20

Example: design of Date ADT

• Consider yet another possible Date specification :public class Date {

private: …;public: Date (int y, int m, int d);

int compareTo (Date that);String toString ();void advance (int n);void advance1Day ();

}• Operation advance1Day is unnecessary.

Prof A Alkhorabi 3- 21

Example: Date data typeA Date class can be built as an ADT:

A Date class that may represent any date (past, present, and future) can be declared as follows:

• Each object of the class:

– a set of values: values for integer types, to represent the Date day, month, and year

– a set of operations: class constructors, and methods to manipulate and inspect and/or update the set of values, isLeap(), equals(), compareTo(), length() and

advance().

• In C++ an ADT is implemented as a class.

Prof A Alkhorabi 3- 22

Example: Date data typeClass declaration:class Date {

// Each Date past, present, or future date, is represented by year, month & a day private :

int day, month, year;public :

Date (int d, int m, int y) { // Construct a date with year y, month m, and day-in-month d. // Throw an exception if they constitute an improper date. if (d < 1 || d > 31 || m < 1 || m > 12)

{ cout << "badly formed date" << endl; throw; } day = d; month = m; year = y;} int isLeap (int y) {// Return true if and only if y is a leap year. return (y%4 == 0 && (y%100 != 0 || y%400 == 0));

}

Prof A Alkhorabi 3- 23

Example: Date data type • Class declaration :

int equals (Date that) { // Return true if this date equal to that, or false otherwise.

return (year == that.year && month == that.month && day == that.day); }

int compareTo (Date that) { // Return -1 if this date comes before that, // or 0 if this date is equal to that, // or +1 if this date come after that.

return ( year < that.year ? -1 :year > that.year ? +1 :month < that. month ? -1 :month < that. month ? +1 :day < that.day ? -1 :day > that.day ? +1 : 0);

}Continue …

Prof A Alkhorabi 3- 24

Example: Date data type • Class declaration :

int length (int m, int y); void advance (int n); void showDate () { // Return this date's ISO string representation. // return (day + "-" + month + "-" + year); cout << day << "-" << month << "-" << year << endl << endl; }

}; // End of class Date

Continue …

Prof A Alkhorabi 3- 25

Example: Date data type• Class declaration (continued):int Date::length (int m, int y) {

// Return the number of days in month m in year y. switch (m) {

case 1: case 3: case 5: case 7:case 8: case 10: case 12:

return 31;case 4: case 6: case 9: case 11:

return 30;case 2:

return (isLeap(y) ? 29 : 28);default:

return -1; }

}

Continue …

Prof A Alkhorabi 3- 26

Example: Date data typeClass declaration :void Date::advance (int n) {// Advance this date by n days (where n >= 0).

int d = day + n, m = month, y = year; int last = length(m, y);

while (d > (last)) { d -= last; if (m < 12) m++; else { m = 1; y++; } // if the same year advance month

// otherwise, advance year and let m=1

} day = d; month = m; year = y;

}

Prof A Alkhorabi 3- 27

Example: Date data type Continue …

• Possible application code:int main (){ // Given a date and number of days advanced, shows new advanced date. Date date1(17, 1, 1960);

date1.showDate(); date1.advance (2000); date1.showDate(); return 0;}

The output Date1.cpp :

17-1-19602-6-1965 Example: Date1.cpp

Date advanced by 2000 days

Prof A Alkhorabi 3- 28

A Person class that may represent any person can be declared as follows:

• Each object of the class:– a set of values: values of string types to

represent the Person surname, forename, and a value for integer to represent the year of birth

– a set of operations: class constructors, and methods to manipulate and inspect and/or update the set of values, changeName(), getPerson(), showPerson().

Example: Person data type

Prof A Alkhorabi 3- 29

Example: Person data typeClass declaration:

class Person {

char *surname, *forename;

int yearOfBirth;

public :

Person(int surname_sz, int forename_sz) { // Constructor

surname = new char[surname_sz];

forename = new char[forename_sz];

};

Person (char *sname, char *fname, int year) {

surname = new char[20];

forename = new char[20];

surname = sname;

forename = fname;

yearOfBirth = year;

};

Prof A Alkhorabi 3- 30

void changeName (char *Newsname, char *Newfname) { surname = Newsname; forename = Newfname;

}; void getPerson(void) {

strcpy(surname, "Hussien");strcpy(forename, "Ahmed");yearOfBirth = 1988;

}; void showPerson(void) {

cout << "Person Name : " << forename << " " << surname << endl << "\nYear of Birth : " << yearOfBirth << endl << endl << endl;

}; ~Person() { // Destructor

delete forename;delete surname;

}};

Example: Person.cpp

Example: Person data type

Prof A Alkhorabi 3- 31

Example: Person data type

• Possible application code:

Person p1 = new Person(“Hussien", “Ahmed", 1980);

Person p2 = new Person(“Abdullah", “Ali", 1867);

However a complete main() function that make use of the class Person follow.

Prof A Alkhorabi 3- 32

Example: Person data type

int main(void){ Person person(15, 15); // Declare a Person object - Constuctor

// & allocate memory to it. person.getPerson(); person.showPerson(); person.changeName("Ali", "Mohammed"); person.showPerson();

Person person2("Jamil", "Abdullah", 1977); // Declare a Person // object - 2nd Constuctor

person2.showPerson();

return 0;}

Example: Person.cpp

Prof A Alkhorabi 3- 33

The output of Person.cppPerson Name : Ahmed Hussien Year of Birth : 1988

Person Name : Mohammed Ali Year of Birth : 1988

Person Name : Abdullah Jamil Year of Birth : 1977

Example: Person data type

Prof A Alkhorabi 3- 34

Strings

• A string is a sequence of characters.

• The characters have consecutive indices.

• A substring of a string is a subsequence of its characters.

• The length of a (sub)string is its number of characters.

• The empty string has length zero.

Prof A Alkhorabi 3- 35

String ADTs

• Assumed requirements:1) The data values are to be strings of any length.2) It must be possible to determine the length of a

string.3) It must be possible to obtain the character at a

given index.4) It must be possible to obtain the substring at a

given range of indices.5) It must be possible to compare strings.6) It must be possible to concatenate strings.

Prof A Alkhorabi 3- 36

Strings: specification

• Possible specification expressed as an outline class declaration:

class String {

// Each String value is an string of characters, // of any length, with indices starting at 0.

private: …;

/////////////// Constructor ////////////

public: String (char[] cs);// Construct a string consisting of all the chars in

cs.

Prof A Alkhorabi 3- 37

Strings: specification

• Possible specification(continued):

int length ();// Return the length of this string.

char charAt (int i);// Return the character at index i in this string.

bool equals (String that);// Return true if and only if this string is equal to that.

int compareTo (String that);// Return –1 if this string is lexicographically less than that, // or 0 if this string is equal to that, // or +1 if this string is lexicographically greater than that.

Prof A Alkhorabi 3- 38

Strings: specification

• Possible specification (continued):

String substring (int i, int j);// Return the substring of this string consisting of the characters // whose indices are between i, …, j–1.

String concat (String that);// Return the string obtained by concatenating this string to that.

}

Prof A Alkhorabi 3- 39

Strings: implementations

• One way to represent a string is by include its length n together with an array of exactly n characters, e.g.:

• Or represent a string by its length n together with a linked list of characters, e.g.:

• The array representation is much easier, but we cannot insert or delete characters.

4 ‘H’ ‘a’ ‘n’ ‘i’3210length

‘H’ ‘a’ ‘n’ ‘i’4length first

Prof A Alkhorabi 3- 40

Strings: implementations

• Write a C++ program that implements the string ADT. The main() function should declare a number of objects of the String class, and use most of the class operations.