www hndit com Data Structures and Algorithms IT

  • Slides: 42
Download presentation
www. hndit. com Data Structures and Algorithms IT 12112 Lecture 02

www. hndit. com Data Structures and Algorithms IT 12112 Lecture 02

Abstract Data Types www. hndit. com � An abstract data type is a mathematical

Abstract Data Types www. hndit. com � An abstract data type is a mathematical set of data, along with operations defined on that kind of data � Examples: �int: it is the set of integers (up to a certain magnitude), with operations +, -, /, *, % �double: it’s the set of decimal numbers (up to a certain magnitude), with operations +, , /, * 2

www. hndit. com Abstract Data Types (Contd. ) n The previous examples belong to

www. hndit. com Abstract Data Types (Contd. ) n The previous examples belong to what is called built-in data types(primitive) n That is, they are provided by the programming language n But new abstract data types can be defined by users, using arrays, enum, structs, classes (if object oriented programming), etc. 3

Data Abstraction www. hndit. com Data abstraction is the process of defining a collection

Data Abstraction www. hndit. com Data abstraction is the process of defining a collection of data and relative operations, by specifying what the operations do on the data, not how the data and the operations are implemented. Example: use of “dates” in a program • In abstract form we think of dates as “Day Month Year” • We identify a number of operations that make sense when applied to a date - the day after a date, the day before a date, equality between two dates, … How might such dates be implemented? 1. Julian form – as the number of days since 1 January 1995 2. With three data fields – year, month, day 2 January 1996 0366 (Julian form) 96 01 02 (Three data field)

www. hndit. com Example of Levels of Data Abstraction Level of Abstraction Example Abstract

www. hndit. com Example of Levels of Data Abstraction Level of Abstraction Example Abstract Data Type List User-defined Data Types Classes Predefined structured Data Types Array of Double Predefined simple Data Types Double Machine Language Type 011011 Abstract Data Types defines data abstraction, which is used to control the interaction between a program and its data structures. It guards against: • Inadvertently erroneous use of the data • Deliberate misuse of the data • Modification of purpose or implementation of shared data

Abstract Data Type (ADT) www. hndit. com • Data types (int, double, boolean etc.

Abstract Data Type (ADT) www. hndit. com • Data types (int, double, boolean etc. ) refer to two things: a data item with certain characteristics and the permissible operations on that data. • The word abstract stands for "considered apart from the detailed specifications or implementation". • An Abstract Data Type (ADT) is more a way of looking at a data structure: focusing on what it does and ignoring how it does its job.

Definitions www. hndit. com An Abstract Data Type is a collection of data together

Definitions www. hndit. com An Abstract Data Type is a collection of data together with a set of data management operations, called Access Procedures, defined on these data. Definition and use of an ADT are independent of the implementation of the data and its access procedures. A Data Structure, or structured data type, is an organised collection of data elements, created using - Predefined structured data types (e. g. , array, vectors) - Predefined simple data types (e. g. Boolean, real, integer) - User-defined data types (e. g. , a “date” class)

www. hndit. com Abstract Data Types (ADTs) An abstract data type (ADT) is an

www. hndit. com Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: – Data stored – Operations on the data – Error conditions associated with operations Example: ADT modeling a simple stock trading system – The data stored are buy/sell orders – The operations supported are order buy(stock, shares, price) order sell(stock, shares, price) void cancel(order) – Error conditions: Buy/sell a nonexistent stock Cancel a nonexistent order 8

www. hndit. com ADTs are not implementations n We can use different implementations for

www. hndit. com ADTs are not implementations n We can use different implementations for ADTs n For instance: Stack – Last in, first out – Basic mechanism for function calls, delimiter checks in compilers, etc. – Operations: new, push, pop, peek, empty?

www. hndit. com Abstract Data Type (ADT) n Vector, Matrix – Random access to

www. hndit. com Abstract Data Type (ADT) n Vector, Matrix – Random access to any element by coordinates n Queue (Buffer) – First in, First out n Set (unordered), Ordered Lists (Dictionary) n Graphs (of nodes and vertices) n …. .

E. g. #include <iostream> www. hndit. com class Vehicle { public: Vehicle() {cout <<

E. g. #include <iostream> www. hndit. com class Vehicle { public: Vehicle() {cout << "Vehicle Constructor" << endl; } virtual ~Vehicle() {cout << "Vehicle Destructor" << endl; } virtual void accelerate() const {cout << "Vehicle Accelerating" << endl; } void set. Acceleration(double a) {acceleration = a; } double get. Acceleration() const {return acceleration; } private: double acceleration; }; class Car: public Vehicle { public: Car() {cout << "Car Constructor" << endl; } virtual ~Car() {cout << "Car Destructor" << endl; } virtual void accelerate() const {cout << "Car Accelerating" << endl; } void drive() const {cout << "Car Driving" << endl; } private: // Car inherits acceleration accessors, member };

int main() { Car my. Car; my. Car. set. Acceleration(9. 81); cout << "Accelerating

int main() { Car my. Car; my. Car. set. Acceleration(9. 81); cout << "Accelerating at " << my. Car. get. Acceleration() << " m/(s*s)"; cout << endl; my. Car. accelerate(); my. Car. drive(); } www. hndit. com

Interface www. hndit. com Interface is the set of operations that define an ADT.

Interface www. hndit. com Interface is the set of operations that define an ADT. n An ADT is defined by the operations that can be performed on it, which is called an interface. n This would often be the public methods. n For example, the interface for a stack consists of these operations: • _init_: Initialize a new empty stack. • push: Add a new item to the stack. • pop: Remove and return an item from the stack. The item that is returned is always the last one that was added. • is. Empty: Check whether the stack is empty. • is. Full: Check whether the stack is full. n

Arrays www. hndit. com Array is a data structure that holds multiple values of

Arrays www. hndit. com Array is a data structure that holds multiple values of the same type placed in contiguous memory locations. Arrays are a way to store and treat collections of items of similar type as a single unit. An array variable identifier refers to this whole unit and it must be declared using a data type. Each element within the array must belong to this type. 14 ICT

www. hndit. com Arrays An array is a list of similar things n An

www. hndit. com Arrays An array is a list of similar things n An array has a fixed: – name – type – length n These must be declared when the array is created. n Arrays sizes cannot be changed during the execution of the code n

Arrays……. n www. hndit. com Arrays – Individual items within an array are referenced

Arrays……. n www. hndit. com Arrays – Individual items within an array are referenced using the array name and an index value. Elements Array Index (Starts with zero) 5 1 2 6 8 3 9 0 1 2 3 4 5 6 16 ICT

www. hndit. com my. Array = 3 6 3 1 6 3 4 1

www. hndit. com my. Array = 3 6 3 1 6 3 4 1 0 1 2 3 4 5 6 7 my. Array has room for 8 elements n The elements are accessed by their index n In Java, array indices start at 0

Arrays (Cont. ) www. hndit. com Declaration of an Arrays are declared using enclosing

Arrays (Cont. ) www. hndit. com Declaration of an Arrays are declared using enclosing square brackets. char vowels[ 5]; Type int number[ 10]; Name of the array Number of elements 18

Accessing the Elements of an Arraywww. hndit. com In any point of a program

Accessing the Elements of an Arraywww. hndit. com In any point of a program in which an array is visible, we can access the value of any of its elements individually as if it was a normal variable, thus being able to both read and modify its value. n The format is : vowels name[index] n a e To define a array char vowels [5]; vowels[0] To input data into first two elements vowels[0] = ‘a’ ; vowels[1] = ‘e’ ; vowels[1] vowels[2] 19

Initialization of an Array 1. www. hndit. com Array Initialization at the time of

Initialization of an Array 1. www. hndit. com Array Initialization at the time of defining Comma-separated list of values enclosed in braces form the elements of an array int powers[5] = {1, 2, 4, 8, 16}; int num[]={3, 99, 2, 25}; 2. The compiler can automatically size the array Initializing after defining the array int powers[5]; powers[0] = 1 ; powers[1] = 2 ; … powers[5] = 16 ; Defining the array Initialization of array elements 20

www. hndit. com Assigning Values n refer to the array elements by index to

www. hndit. com Assigning Values n refer to the array elements by index to store values in them. my. Array[0] = 3; my. Array[1] = 6; my. Array[2] = 3; . . . n can create and initialise in one step: int my. Array[] = {3, 6, 3, 1, 6, 3, 4, 1};

Take out data from an array char vowels [5]; www. hndit. com vowels a

Take out data from an array char vowels [5]; www. hndit. com vowels a e i o u 0 1 2 3 4 n To access single element from the array cout << vowels[1]; // will output letter ‘e’ n To access all elements from the array is easy with for loop. for (int i=0; i<=4; i++) cout<<vowels[i]; 22

E. g: Store vowels in a array and printing themwww. hndit. com (Method 1)

E. g: Store vowels in a array and printing themwww. hndit. com (Method 1) #include<iostream> using namespace std; int main(){ char vowels [5]; vowels[0] = 'a' ; vowels[1] = 'e' ; vowels[2] = 'i' ; vowels[3] = 'o' ; vowels[4] = 'u' ; return 0; } cout<<"Element 0 = cout<<"Element 1 = cout<<"Element 2 = cout<<"Element 3 = cout<<"Element 4 = Store values into array "<<vowels[0]<<endl; "<<vowels[1]<<endl; "<<vowels[2]<<endl; "<<vowels[3]<<endl; "<<vowels[4]<<endl; Printing array elements 23

E. g: Store vowels in a array and printing themwww. hndit. com (Method 2)

E. g: Store vowels in a array and printing themwww. hndit. com (Method 2) #include<iostream> using namespace std; int main(){ char vowels[5] = {'a', 'e', 'i', 'o', 'u'} ; Store values at the time of defining Printing array elements using a for loop for (int i=0; i<=4; i++) cout<<"Element "<< i<<" = " <<vowels[i]<<endl; return 0; } 24

www. hndit. com � #include <iostream> int main() { int n[ 10 ]; for

www. hndit. com � #include <iostream> int main() { int n[ 10 ]; for ( int i = 0; i < 10; i++ ) n[ i ] = 0; for ( int j = 0; j < 10; j++ ) cout << n[ j ] << endl; return 0; } 25

Exercises www. hndit. com 1. Write a program to initialize an array with 10

Exercises www. hndit. com 1. Write a program to initialize an array with 10 character elements (A. . J) and display characters in the reverse order. 2. Define an array to store five integers from the keyboard. Calculate the sum of numbers stored in the array and display the sum. 26

Searching www. hndit. com n The simplest type of searching process is the sequential

Searching www. hndit. com n The simplest type of searching process is the sequential search. In the sequential search, each element of the array is compared to the key, in the order it appears in the array, until the first element matching the key is found. n If you are looking for an element that is near the front of the array, the sequential search will find it quickly. The more data that must be searched, the longer it will take to find the data that matches the key using this process. 27

#include <iostream. h> www. hndit. com int main(void) { //”filling the array” int array[5]

#include <iostream. h> www. hndit. com int main(void) { //”filling the array” int array[5] = {20, 12, 40, 23}; cout<< "Enter the number you want to find “; int key; cin>> key; int flag = 0; // set flag to off 28

// start to loop through the array www. hndit. com for(int i=0; i<10; i++)

// start to loop through the array www. hndit. com for(int i=0; i<10; i++) { if (array[i] == key) // if match is found { flag = 1; // turn flag on break ; // break out of for loop } } 29

www. hndit. com if (flag) // if flag is TRUE (1) { cout<< "Your

www. hndit. com if (flag) // if flag is TRUE (1) { cout<< "Your number is at subscript position " << i <<". n"; } else { cout<< "Sorry, I could not find your number in this array. "<<endl; } return 0; } 30

Deleting www. hndit. com n Firstly , you find the element that you want

Deleting www. hndit. com n Firstly , you find the element that you want to delete and find the index. n so, just set the value of that cell to “ 0” (or NULL). If you mean to get rid of that element, you'd need to shift all the ones to the right of that element one to the left: 31

www. hndit. com for (int i = index; i < /* length */; i++)

www. hndit. com for (int i = index; i < /* length */; i++) { array[i] = array[i+1]; } 32

www. hndit. com Notes on Arrays n index starts at 0. n arrays can’t

www. hndit. com Notes on Arrays n index starts at 0. n arrays can’t shrink or grow. – e. g. , use Vector instead. n each element is initialized.

Multi Dimensional Arrays www. hndit. com Multidimensional arrays can be described as "arrays of

Multi Dimensional Arrays www. hndit. com Multidimensional arrays can be described as "arrays of arrays". For example, a bidimensional array can be imagined as a bidimensional table made of elements, all of them of a same uniform data type. int two. DMatrix [ 2][ 3]; 0 int two. DMatrix [2 ][3 ] = { {5, 3, 2}, {8, 4, 1} }; Each element can be changed as follows two. DMatrix [0][0] = 5; two. DMatrix [1][2] = 1; 1 2 0 5 3 2 1 8 4 1 [0][0] [1][2] ICT 34

www. hndit. com E. g. #include <iostream> using namespace std; int main() { String[][]

www. hndit. com E. g. #include <iostream> using namespace std; int main() { String[][] names = {{"Mr. ", "Mrs. ", "Ms. "}, {"Smith", "Jones"}}; cout<<names[0][0] << names[1][0]<<endl; //Mr. Smith cout<<names[0][2]<< names[1][1]; //Ms. Jones } }

Arrays www. hndit. com Example program #include <iostream> using namespace std; int main() {

Arrays www. hndit. com Example program #include <iostream> using namespace std; int main() { double m[][]={ {0*0, 1*0, 2*0, 3*0}, {0*1, 1*1, 2*1, 3*1} {0*2, 1*2, 2*2, 3*2} {0*3, 1*3, 2*3, 3*3}}; for(int i=0; i<4; i++){ for(int j=0; j<4; j++){ cout<<m[i][j]<< “ ”<<endl; } } }

Array Limitations www. hndit. com n Arrays – Simple, – Fast but – Must

Array Limitations www. hndit. com n Arrays – Simple, – Fast but – Must specify size at construction time – Murphy’s law • Construct an array with space for n – n = twice your estimate of largest collection • Tomorrow you’ll need n+1 – More flexible system?

Vectors www. hndit. com Arrays are fixed in size at declaration time – cannot

Vectors www. hndit. com Arrays are fixed in size at declaration time – cannot grow or shrink dynamically during run time n C++ provides a Vector class which can grow or shrink during the run of the program n n Vectors are declared with the following syntax: vector<type> variable_name (number_of_elements); n The number of elements is optional. You could declare it like this: vector<type> variable_name;

www. hndit. com Below are several examples of vector declarations: vector<int> values (5); //

www. hndit. com Below are several examples of vector declarations: vector<int> values (5); // Declares a vector of 5 integers vector<double> grades (20); // Declares a vector of 20 doubles vector<string> names; // Declares a vector of strings, // initially empty (contains 0 strings)

Arrays Vs Vectors www. hndit. com n Because Vectors are dynamically-allocated, they offer a

Arrays Vs Vectors www. hndit. com n Because Vectors are dynamically-allocated, they offer a relatively memory-efficient way of handling lists whose size could change drastically. E. g. : Line buffer of a text. n Moreover, Vectors have some useful member functions that make coding simpler. E. g. : insert. Element. At n But because the Vector class is based on an array of object references, these methods are generally no more efficient than array-based algorithms. The insert method must perform multiple "swap" operations just as an array 'insert‘ algorithm would. n Thus, Vectors are easier to use than arrays for most applications, but they do not offer all the performance advantages of fully-dynamic storage.

E. g. www. hndit. com // constructing vectors #include <iostream> #include <vector> int main

E. g. www. hndit. com // constructing vectors #include <iostream> #include <vector> int main () { unsigned int i; // constructors used in the same order as described above: vector<int> first; // empty vector of ints vector<int> second (4, 100); // four ints with value 100 vector<int> third (second. begin(), second. end()); // iterating through second vector<int> fourth (third); // a copy of third // the iterator constructor can also be used to construct from arrays: int myints[] = {16, 2, 77, 29}; vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) ); cout << "The contents of fifth are: "; for (i=0; i < fifth. size(); i++) cout << " " << fifth[i]; Output cout << endl; The contents of fifth are: 16 2 77 29 return 0; }

E. g. #include <iostream> #include <vector> www. hndit. com int main(int argc, char** argv)

E. g. #include <iostream> #include <vector> www. hndit. com int main(int argc, char** argv) { /* Initialize vector of 10 copies of the integer 5 */ vector<int> vector. One(10, 5); /* Display size of vector */ cout << "Size of vector is " << vector. One. size() << " elements. " << endl; /* run through the vector and display each element, using size() to determine index boundary */ for (long index=0; index<(long)vector. One. size(); ++index) { cout << "Element " << index << ": " << vector. One. at(index) << endl; } /* Change size of vector - element removal */ vector. One. resize(7); /* Display size of vector */ cout << "Size of vector is " << vector. One. size() << " elements. " << endl; /* run through the vector and display each element, using size() to determine index boundary */ for (long index=0; index<(long)vector. One. size(); ++index) { cout << "Element " << index << ": " << vector. One. at(index) << endl; } return EXIT_SUCCESS;