Lecture DS & Algorithms:09 Abstract Data Types. Lecture DS & Algorithms:09 2 Abstract Data Types...

Post on 12-Jan-2016

221 views 0 download

transcript

Lecture DS & Algorithms:09

Abstract Data Types

Lecture DS & Algorithms:09

2

Abstract Data Types

Data Type: A data type is a collection of values and a set of operations

on those values.

The collection and operations form a mathematical construct

An ADT refers to the mathematical concept that defines the data type

Each ADT operation is defined by its inputs and outputs.

Lecture DS & Algorithms:09

3

Def.

e.g. whole numbers (integers) and arithmetic operators for addition, subtraction, multiplication and division.

e.g. Flight reservation Basic operations: find empty seat, reserve a seat,

cancel a seat assignmentWhy "abstract?" Data, operations, and relations are studied

independent of implementation.

What not how is the focus.

a collection of related data items together with an associated set of operations

Abstract Data Types

Lecture DS & Algorithms:09

4

Def.Consists of

storage structures (data structures) to store the data items

andalgorithms for the basic operations.

The storage structures/data structures used in implementations are provided in a language (primitive or built-in) or are built from the language constructs (user-defined).

In either case, successful software design uses data abstraction:

Separating the definition of a data type from its implementation.

Abstract Data Types

Lecture DS & Algorithms:09

5

Separation of interface and implementation

• Think of ADT as a black box

• ADT is represented by an interface and implementation is hidden from the user

– This means that the ADT can be implemented in various ways, as long as it adheres to interface

– For example, a ListADT can be represented using an array based implementation or a linked list implementation

Lecture DS & Algorithms:09

6

Linear list data structure

• Def: An ordered collection of elements– some examples are an alphabetized list of students, a list of gold

medal winners ordered by year, etc.

• With these examples in mind, we feel the need to perform the following operations on a linear list

– Determine whether the list is empty– Determine the size of list– Find the element with a given index– Find the index of a given element– Delete an element given its index– Insert a new element

Lecture DS & Algorithms:09

7

ADT - linearList

• The ADT specification is independent of any representation and programming language

AbstractDataType linearList{

elementsordered finite collection of zero or more elements

operationsempty(): return true if the list is emptysize(): return the list sizeget(index): return the indexed elementindexOf(x): return the index of the first occurance of x in

the list, returns -1, if x is not in the listerase(index): delete the indexth element, element with higher

index have their index reduced by 1insert(index, x): insert x as the indexth elementoutput(): output the list elements from left to right

Lecture DS & Algorithms:09

8

Array representation

• [5, 2, 4, 8,1]• Some of the implementations can be

18425location(i) = i

52481location(i) = 9- i

42518location(i) = (7+i)%10

Lecture DS & Algorithms:09

Simple Data Types

Also known as built-in data types

Lecture DS & Algorithms:09

10

Boolean data

Data values: {false, true}

In C/C++: false = 0, true = 1 (or nonzero)

Operations: and &&or ||not !

x !x0 11 0

&& 0 1

0 0 0

1 0 1

| | 0 1

0 0 1

1 1 1

Lecture DS & Algorithms:09

11

Character Data

Store numeric codes (ASCII, EBCDIC, Unicode)

1 byte for ASCII and EBCDIC,

2 bytes for Unicode

Basic operation: comparison to determine if Equal, Less than, Greater than, etc. use their numeric value.

,

ASCII/EBCDIC

Unicode

Lecture DS & Algorithms:09

12

Integer Data

Non-negative (unsigned) integer:

Store its base-two representation in a fixed number w of bits

(e.g., w = 16 or w = 32)

88 = 00000000010110002

Signed integer: Store in a fixed number w of bits using one of the following

representations:

Lecture DS & Algorithms:09

13

Sign-magnitude representation

Save one bit (usually most significant) for sign

(0 = +, 1 = – )

Use base-two representation in the other bits.

88 _000000001011000

0sign bit

–88 _0000000010110001

Lecture DS & Algorithms:09

14

Two's complement representation

For negative n (–n):(1) Find w-bit base-2 representation of n (2) Complement each bit.(3) Add 1

Example: –881. 88 as a 16-bit base-two number000000000101100

0

Same as sign mag.

For nonnegative n: Use ordinary base-two representation with leading (sign) bit 0

2. Complement this bit string3. Add 1

11111111101001111111111110101000

Lecture DS & Algorithms:09

Array ADT

Lecture DS & Algorithms:09

16

Linear Arrays

• A linear array is a finite number N homogeneous data elements

– Elements are referenced respectively by an index set of N consecutive numbers

– Elements are stored respectively in successive memory locations

– Fixed number of elements

• Index always integer

• Length=UB-LB+1

• Notation A1 or A(1) or A[1]

Lecture DS & Algorithms:09

17

Declaring arrays in C++

whereelement_type is any typearray_name is the name of the array — any valid identifierCAPACITY (a positive integer constant) is the number of

elements in the array

score[0]

score[1]

score[2]

score[3]

score[99]

.

.

....

element_type array_name[CAPACITY];

e.g., double score[100];

The elements (or positions) of the array are indexed 0, 1, 2, . . ., CAPACITY - 1.

Can't input the capacity, Why?

The compiler reserves a block of “consecutive” memory locations, enough to hold CAPACITY values of type element_type.

Lecture DS & Algorithms:09

18

indices numbered 0, 1, 2, . . ., CAPACITY - 1

How well does C/C++ implement an array ADT?

As an ADT In C++

ordered

fixed size

same type elements

direct access

element_type is the type of elements

CAPACITY specifies the capacity of the array

subscript operator []

Lecture DS & Algorithms:09

19

an array literal

Array Initialization

Example:double rate[5] = {0.11, 0.13, 0.16, 0.18, 0.21};

Note 1: If fewer values supplied than array's capacity, remaining elements assigned 0.

double rate[5] = {0.11, 0.13, 0.16};

rate

0 1 2 3 4

0.11 0.13 0.16 0 0

rate

0 1 2 3 4

0.11 0.13 0.16 0.18 0.21

In C++, arrays can be initialized when they are declared.Numeric arrays:element_type num_array[CAPACITY] = {list_of_initial_values};

Lecture DS & Algorithms:09

20

Note 1: If fewer values are supplied than the declared size of the array, the zeroes used to fill un-initialized elements are interpreted as the null character '\0' whose ASCII code is 0.

const int NAME_LENGTH = 10;char collegeName[NAME_LENGTH]={'C', 'a', 'l', 'v', 'i', 'n'};

vowel

0 1 2 3 4

A E I O U

char vowel[5] = {'A', 'E', 'I', 'O', 'U'};

Character Arrays

Character arrays may be initialized in the same manner as numeric arrays.

declares vowel to be an array of 5 characters and initializes it as

follows:

collegeName

0 1 2 3 4 5 6 7 8 9

C a l v i n \0 \0 \0 \0

Lecture DS & Algorithms:09

21

The contents of the memory word with this address 0x13BA can then be retrieved and displayed.

An address translation like this is carried out each time an array element is accessed.

What will be the time complexity

AddressesWhen an array is declared, the address of the first byte (or word) in the block of memory associated with the array is called the base address of the array.

Each array reference must be translated into an offset from this base address.

For example, if each element of array score will be stored in 8 bytes and the base address of score is 0x1396. A statement such as

cout << score[3] << endl;requires that array reference score[3] be translated into a memory address: 0x1396 + 3 * sizeof (double)

= 0x1396 + 3 * 8 = 0x13BA

score[3]

[0]

[1]

[2]

[3]

[99]

.

.

....

score 0x1396

0x13ae

Lecture DS & Algorithms:09

22

The value of array_name is actually the base address of array_name

array_name + index is the address of array_name[index].

An array reference array_name[index]

is equivalent to

For example, the following statements of pseudocode are equivalent:

print score[3]print *(score + 3)

* is the dereferencing operator*ref returns the contents of the memory location with address ref

*(array_name + index)

Character arrays

Lecture DS & Algorithms:09

23

Operations

• Traverse• Insert• Delete• Search

– Linear Search– Binary Search

• Sorting

Lecture DS & Algorithms:09

24

Traversing Linear Arrays

Repeat for K=LB to UB

Apply PROCESS to Array[K]

[End of Loop]

Exit

Lecture DS & Algorithms:09

25

Sorting

BUBBLE(DATA,N)1. Repeat Steps 2 and 3 for K=1 to N-1

2. Set PTR:=13. Repeat while PTR<=N-K

a) if DATA[PTR]>DATA[PTR+1] then:Swap DATA[PTR] and DATA [PTR+1]

b) Set PTR:=PTR+14. Exit

Complexity of Bubble Sort?n(n-1)/2 + O(n)=?Can you see any problem?How to make bubble sort efficient?

Lecture DS & Algorithms:09

26

Bubble Sort Source Code

for(x = 0; x < n; x++)

{ for(y = 0; y < n-1; y++)

{

if(array[y] > array[y+1])

{

temp = array[y+1];

array[y+1] = array[y];

array[y] = temp;

}

}

}

Lecture DS & Algorithms:09

27

• void bubbleSort(int numbers[], int array_size) • {• int i, j, temp; • for (i = (n - 1); i >= 0; i--) • { • for (j = 1; j <= i; j++) • { • if (numbers[j-1] > numbers[j]) • { • temp = numbers[j-1]; • numbers[j-1] = numbers[j]; • numbers[j] = temp; • } • }• }• }

Lecture DS & Algorithms:09

28

Bubble Sort: Example

• Consider the unsorted array to the right

• We start with the element in the first location, and move forward:– if the current and next items are in

order, continue with the next item, otherwise

– swap the two entries

Lecture DS & Algorithms:09

29

Bubble Sort: Example

• After one loop, the largest element is in the last location

• Repeat the procedure

Lecture DS & Algorithms:09

30

Bubble Sort: Example

• Now the two largest elements are at the end

• Repeat again

Lecture DS & Algorithms:09

31

Bubble Sort: Example

• With this loop, 12 is brought to its appropriate location

Lecture DS & Algorithms:09

32

Bubble Sort: Example

• Finally, we swap the last two entries to order them

• At this point, we have a sorted array

Lecture DS & Algorithms:09

33

Problems with arrays

• Capacity can not be changed during program execution– Memory wastage– Out of range errors