Download Data Structures and Algorithms IT2003

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Comparison of programming languages (associative array) wikipedia , lookup

Array data structure wikipedia , lookup

Transcript
www.hndit.com
Data Structures and Algorithms
IT12112
Lecture 02
www.hndit.com
Abstract Data Types
 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.)
The previous examples belong to what
is called built-in data types(primitive)
 That is, they are provided by the
programming language
 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 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 Data Type
List
User-defined Data Types
Classes
Predefined structured Data Types
Array of Double
Predefined simple Data Types
Double
Machine Language Type
0110111011
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.) 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 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 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
We can use different implementations for
ADTs
 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)

Vector, Matrix
– Random access to any element by
coordinates

Queue (Buffer)
– First in, First out
Set (unordered), Ordered Lists (Dictionary)
 Graphs (of nodes and vertices)
 …..

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 setAcceleration(double a) {acceleration = a;}
double getAcceleration() 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 myCar;
myCar.setAcceleration(9.81);
cout << "Accelerating at " <<
myCar.getAcceleration() << " m/(s*s)";
cout << endl;
myCar.accelerate();
myCar.drive();
}
www.hndit.com
Interface




www.hndit.com
Interface is the set of operations that define an ADT.
An ADT is defined by the operations that can be
performed on it, which is called an interface.
This would often be the public methods.
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.
• isEmpty: Check whether the stack is empty.
• isFull: Check whether the stack is full.
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
An array has a fixed:
– name
– type
– length
These must be declared when the array is created.
Arrays sizes cannot be changed during the execution
of the code
Arrays…….

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
myArray =
3
6
3
1
6
3
4
1
0
1
2
3
4
5
6
7
myArray has room for 8 elements
 The elements are accessed by their index
 In Java, array indices start at 0
Arrays (Cont.)
www.hndit.com
Declaration of an Array
Arrays are declared using enclosing square brackets.
char vowels[ 5];
Type
Name of the array
int number[ 10];
Number of elements
18
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.
The format is :
vowels
name[index]
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 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

refer to the array elements by index to store values in
them.
myArray[0] = 3;
myArray[1] = 6;
myArray[2] = 3; ...

can create and initialise in one step:
int myArray[] = {3, 6, 3, 1, 6, 3, 4, 1};
Take out data from an array
www.hndit.com
vowels
char vowels [5];
a e i
o u
0 1 2 3 4

To access single element from the array
cout << vowels[1]; // will output letter ‘e’

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)
#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' ;
cout<<"Element 0 =
cout<<"Element 1 =
cout<<"Element 2 =
cout<<"Element 3 =
cout<<"Element 4 =
return 0;
}
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)
#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 ( int i = 0; i < 10; i++ )
n[ i ] = 0;
for ( int j = 0; j < 10; j++ )
cout << n[ j ] << endl;
return 0;
}
25
www.hndit.com
Exercises
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

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.

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
www.hndit.com
#include <iostream.h>
int main(void)
{
//”filling the array”
int array[5] = {20,10,12,40,23};
cout<< "Enter the number you want to find “;
int key;
cin>> key;
int flag = 0; // set flag to off
28
www.hndit.com
// start to loop through the array
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 number is at subscript position "
<< i <<".\n";
}
else
{
cout<< "Sorry, I could not find your number in
this array."<<endl<<endl;
}
return 0;
}
30
www.hndit.com
Deleting
Firstly ,you find the element that you want
to delete and find the index.
 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++)
{
array[i] = array[i+1];
}
32
www.hndit.com
Notes on Arrays
index starts at 0.
 arrays can’t shrink or grow.

– e.g., use Vector instead.

each element is initialized.
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 twoDMatrix [ 2][ 3];
0
int twoDMatrix [2 ][3 ] = { {5,3,2},{8,4,1} };
Each element can be changed as follows
twoDMatrix [0][0] = 5;
twoDMatrix [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[][] 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()
{
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
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 grow or shrink dynamically during run
time
 C++ provides a Vector class which can grow
or shrink during the run of the program

Vectors are declared with the following syntax:
vector<type> variable_name (number_of_elements);

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);
// 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

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.

Moreover, Vectors have some useful member functions
that make coding simpler. E.g.: insertElementAt

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.

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 ()
{
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) {
/* Initialize vector of 10 copies of the integer 5 */
vector<int> vectorOne(10,5);
/* Display size of vector */
cout << "Size of vector is " << vectorOne.size() << " elements." << endl;
/* run through the vector and display each element, using size() to determine index boundary */
for (long index=0; index<(long)vectorOne.size(); ++index) {
cout << "Element " << index << ": " << vectorOne.at(index) << endl;
}
/* Change size of vector - element removal */
vectorOne.resize(7);
/* Display size of vector */
cout << "Size of vector is " << vectorOne.size() << " elements." << endl;
/* run through the vector and display each element, using size() to determine index boundary */
for (long index=0; index<(long)vectorOne.size(); ++index) {
cout << "Element " << index << ": " << vectorOne.at(index) << endl;
}
return EXIT_SUCCESS;