Você está na página 1de 62

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Q1) Basic concepts of Object-oriented programming


The principal enhancement being the object oriented concept of a class. A Class is a user defined type that encapsulates many important mechanisms. Classes enable programmers to break an application up into small, manageable pieces, or objects. Object: Objects are the basic run time entities in an object-oriented system. They may represent a person, a place, a bank account, a table of data or any item that the program has to handle. Class: The entire set of data and code of an object can be made of a user defined data type with the help of a class in fact Objects are variables of the type class. Once a class has been defined, we can create any number of objects belonging to that class. A class is thus a collection of objects of similar type. For example: mango, apple, and orange are members of the class fruit. ex: fruit mango; will create an object mango belonging to the class fruit. Data Abstraction and Encapsulation: The wrapping up of data and functions in to a single unit is known as encapsulation. Data encapsulation is the most striking feature of a class. The data is not accessible to the outside world and only those functions which are wrapped in the class can access. This insulation of the data from direct access by the program is called data hiding. Abstraction: Abstraction refers to the act of representing essential features without including the background details or explanations. since the classes use the concept of data abstraction ,thy are known as abstraction data type(ADT).
S.SANTHI PRIYA UNIT 1 NOTES 1

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Inheritance: Inheritance is the process by which objects of one class acquire the properties of Polymorphism: objects of another class. The concept of inheritance provides the idea of reusability. polymorphism is another important oop concept. Polymorphism means the ability to take more than one form. An operation may exhibit different instances. The process of making an operator to exhibit different behaviours in different instance is known as operator overloading. Benefits of object oriented programming: Data security is enforced. Inheritance saves time. User defined data types can be easily constructed. Inheritance emphasizes inventions of new data types.

Large complexity in the software development cn be easily managed

Q2)CLASSES
DEF: Class is a user defined data type which binds data and functions together. A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions.In C++, a class is declared using the class keyword. The syntax of a class declaration is similar to that of a structure. Its general form is, class class-name { // private functions and variables access specifier: // public functions and variables };

S.SANTHI PRIYA

UNIT 1 NOTES

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

A function declared inside a class is a member function. An access specifier is one of the following three keywords: private, public or protected. These specifiers modify the access rights that the members following them acquire: private members of a class are accessible only from within other members of the same class or from their friends. protected members are accessible from members of their same class and from their friends, but also from members of their derived classes. Finally, public members are accessible from anywhere where the object is visible. By default, all members of a class declared with the class keyword have private access for all its members. Therefore, any member that is declared before one other class specifier automatically has private access.

Q3)

Constructors and destructors

Constructors: It is convenient if any object can initialize itself when it is first created, without the need to make a separate call to its member functions. C++ provides a non static member function called as the constructor that is automatically called when an object is created. After objects are created, their members can be initialized by using constructors. The general form or the syntax of a constructor is Class_name (arguments); where class_name is the name of the constructor, which is the same as that of class in which it exists arguments can also be passed to a

S.SANTHI PRIYA

UNIT 1 NOTES

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

constructor. There can be more than one constructor in a class. Constructor can not specify return types nor return values. Ex: #include<iostream.h> class maths { int a; public: maths() { cout<<\n This is a constructor; a=100; } void showdata() { cout<<\n <<a; } }; void main() { maths m; m.showdata(); } A constructor is a special member function which has the same name as the class. Constructors are used to initialize the class and are automatically called when the objects are created. The value of a=

S.SANTHI PRIYA

UNIT 1 NOTES

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Important points to be noted while using Constructors: Constructor name must be the same as that of its class name in which it belongs. Constructors created. Constructors should have public access within the class. Constructors can not be declared as static or Const. Constructors can not specify return types nor return values. Constructors can be overloaded to provide many different forms for initializing the objects of a class. are invoked automatically when objects are

Default Constructor: If a constructor takes no arguments it is called as no argument constructor or Default constructor. This constructor has public access within the class and essentially does nothing useful. Parameterized Constructor: We can initialize the data members of a class with different values when they are created. This is achieved by passing arguments to the constructor functions when the objects are created. This is achieved by passing arguments to the constructor functions when the objects are created. Such constructors are referred to as parameterized constructors. Ex: #include<iostream.h> class product { int x,y; public: product(int a, int b)
S.SANTHI PRIYA UNIT 1 NOTES 5

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

{ x=a; y=b; } void putdata() { cout<<\n Value of x:<<x; cout<<\n value of y :<<y; } }; main() { product p(5,10); p.putdata(); } Copy constructor: Copy constructor is a constructor function designed to copy objects of the same class type. It accepts a single argument and returns a copy of objects. A copy constructor is called when ever the constructor passes an object to a function by value. It can also be called if you initialize a new object with another object of the same type. The process of initializing an object using copy constructor is called as copy initialization. We can define and at the same time initialize an object to the value of another object in two forms: Class_name.obj1(obj2); Class_name.obj1=obj2; Destructors Destructors: A destructor is a member function that is called automatically when an object is destroyed. Syntax for destructor function is:
S.SANTHI PRIYA UNIT 1 NOTES 6

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

~class name (); Where the class name is the name of the destructor (which is same as the name of the constructor i.e. name of the class) and is preceded by tilde (~) symbol. A Destructor is normally used for releasing dynamically allocated memory that was already allocated for an object by the constructor. Like constructors, destructors do not have a return value. Although system provides a default constructor, it is considered as a good programming practice to define a destructor before the end of each class definition. A destructor doesnt receive arguments and hence it can not be overloaded. Each class has one destructor. Ex: #include<iostream.h> class cal {public: call() { cout<<\n This is a constructor; } ~call() { cout<<\n This is a destructor; } }; void main() { cal c; }
S.SANTHI PRIYA UNIT 1 NOTES 7

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Constructors: A constructor function is a special function that is a member of a class and has the same name as that of class. It is very common for some part of an object to require initialization before it can be used. This automatic initialization is performed through the use of a constructor function. C++ provides a default constructor for each class, which is a constructor with no parameters. But, one can define multiple constructors for the same class, and may even redefine the default constructor An Objects constructor is automatically called when the object is created.

Destructors: The complement of the constructor is the destructor. When an object is destroyed, its destructor (if it has one) is automatically called. There are many reasons why a destructor function may be needed. For example, an object may need to deallocate memory that it had previously allocated or it may need to close a file that it had opened. In C++, it is the destructor function that handles deactivation events. The destructor has the same name as the constructor, but it is preceded by a ~. C++ provides a default destructor for each class The default simply applies the destructor on each data member. But we can redefine the destructor of a class. A C++ class can have only one destructor. One can redefine the destructor of a class.
S.SANTHI PRIYA UNIT 1 NOTES 8

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

A C++ class can have only one destructor

Q4) INLINE FUNCTIONS & Static Class Members


Any function defined within a class body is inline. We can also make a non-class function inline by preceding it with the inline keyword. Include the function body with the declaration; otherwise the compiler will treat it as an ordinary function declaration. The successful approach provides the function body. To define an inline function, you must ordinarily precede the function definition with the inline keyword. However, this is not necessary inside a class definition. Any function you define inside a class is inline function When a function is declared inline, the function is expanded at the calling block. The function is not treated as a separate unit like other normal functions. But a compiler is free to decide, if a function qualifies to be an inline function. If the inline function is found to have larger chunk of code, it will not be treated as an inline function, but as like other normal functions. In fact, the keyword inline is not necessary. If the function is defined with its body directly and the function has a smaller block of code, it will be automatically treated as inline by the compiler. As implied, inline functions are meant to be used if there is a need to repetitively execute a small block of code, which is smaller. When such functions are treated inline, it might result in a significant performance difference. //Inline Function
S.SANTHI PRIYA UNIT 1 NOTES 9

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

#include <iostream> inline int max(int a, int b) { return (a>b ? a : b) } Void main() { cout << max(10, 20); cout << "\n max is " << max(99, 88); } Static Class Members: Member variables declared static are shared between all instances of an object type. This means that only one copy of the variable exists for any object type i.e. only one copy of that variable for all objects of the class, and all objects will share that variable. No matter how many objects of a class are created, only one copy of a static data member exists. A static member variable exists before any object of its class is created Static Member Functions Member functions declared static are shared between all instances of an object type. This means that only one copy of the member function exists for any object type.

Q5) This Pointer

S.SANTHI PRIYA

UNIT 1 NOTES

10

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

When you are writing code in a member function, the predefined variable this contains a pointer to the current object. Any member element, for example x, can be referenced in two ways: X=10; This->x=10; // same as above References to members are usually written without this because there is no need to use it; however, there are situations where this is needed. The primary use of this is to return a pointer to the current object, or to pass the object to a function. Ex: #include<iostream.h> #include<conio.h> class ptr { int a; public: void ex() { a=10; cout<<"\n value of this->a } }; void main() { ptr p; clrscr(); p.ex();
S.SANTHI PRIYA UNIT 1 NOTES 11

is "<<this->a;

cout<<"\n value of (*this).a is <<(*this).a;

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

getch(); }

Q6) Friend Functions


Friend functions are functions defined outside a class (i.e., not member functions), but which the class declares to be friends so that they can use the class's private members. A class doesn't control the scope of friend functions so friend function declarations are usually written at the beginning of a .h file. Public and private don't apply to them. friend functions can access the private members directly they can avoid the cost of using getter functions. However, never do this unless you really need to because it makes code harder to read and introduces more possible sources of errors thru increased dependencies. It is possible to grant a nonmember function access to the private members of a class by using a Friend. A friend function has access to all private and protected members of the class for which it is a friend. To declare a friend function, include its prototype within the class, preceding it with the keyword friend. Ex: #include<iostream.h> #include<conio.h> class exam { int a,b;
S.SANTHI PRIYA UNIT 1 NOTES 12

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

public: void getdata(); friend int sum(exam x); }; void exam::getdata() { cout<<"\n enter two numbers"; cin>>a>>b; } int sum(exam z) { cout<<"\n exmple for friend function"; return(z.a+z.b); } void main() { exam m; m.getdata(); cout<<"\n sum is "<<sum(m); }

Q7) Dynamic Memory allocation and Deallocation


C++ provides two dynamic allocation operators: new and delete. These operators are used to allocate and free memory at run time. However, for C++ code, we use the new and delete operators because they have several advantages. The new operator allocates memory and returns a pointer to the start of it. The delete operator frees memory previously allocated using new.
S.SANTHI PRIYA UNIT 1 NOTES 13

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

The general forms of new and delete are shown here: p_var = new type; delete p_var; Here, p_var is a pointer variable that receives a pointer to memory that is large enough to hold an item of type Allocating memory using new Point *p = new Point (5, 5); new can be thought of a function with slightly strange syntax new allocates space to hold the object. new calls the objects constructor. new returns a pointer to that object. Deallocating memory using delete // allocate memory Point *p = new Point(5, 5); ... // free the memory delete p; For every call to new, there must be exactly one call to delete. Using new with arrays int x = 10; int* nums1 = new int[10]; // ok int* nums2 = new int[x]; // ok Initializes an array of 10 integers on the heap. Using new with multidimensional arrays int x = 3, y = 4; int* nums3 = new int[x][4][5];// ok
S.SANTHI PRIYA UNIT 1 NOTES 14

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Initializes a multidimensional array Only the first dimension can be a variable. The rest must be constants. Use single dimension arrays to fake multidimensional ones Using delete on arrays // allocate memory int* nums1 = new int[10]; int* nums3 = new int[x][4][5]; ... // free the memory delete[] nums1; delete[] nums3; Have to use delete [].

Q8) Exceptional Handling


Any Unusual condition in the program is called as exception. Code part that handles exceptions is known as exception handler. The mechanism that implements exception handler is called exception handling. C++ provides built in facility for handling error conditions. Code that you want to monitor for exceptions must have been executed from within a try block. (Functions called from within a try block may also throw an exception.)

S.SANTHI PRIYA

UNIT 1 NOTES

15

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Exceptions that can be thrown by the monitored code are caught by a catch statement, which immediately follows the try statement in which the exception was thrown. The general form of try and catch are shown here. try { // try block } catch (type1 arg) { // catch block } catch (type2 arg) { // catch block } catch (type3 arg) { // catch block } .. catch (typeN arg) { // catch block } Try The try can be as short as a few statements within one function or as all encompassing as enclosing the main() function code within a try block (which effectively causes the entire program to be monitored). Catch When an exception is thrown, it is caught by its corresponding catch statement, which processes the exception. There can be more than one catch statement associated with a try.
S.SANTHI PRIYA UNIT 1 NOTES 16

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Which catch statement is used is determined by the type of the exception. That is, if the data type specified by a catch matches that of the exception, then that catch statement is executed (and all others are bypassed). When an exception is caught, arg will receive its value. Any type of data may be caught, including classes that you create. If no exception is thrown (that is, no error occurs within the try block), then no catch statement is executed. Throw The general form of the throw statement is shown here: throw exception; throw generates the exception specified by exception. If this exception is to be caught, then throw must be executed either from within a try block itself, or from any function called from within the try block (directly or indirectly). If you throw an exception for which there is no applicable catch statement, an abnormal program termination may occur. Throwing an unhandled exception causes the standard library function terminate() to be invoked. Catching All Exceptions In some circumstances you will want an exception handler to catch all exceptions instead of just a certain type. catch(...) { // process all exceptions } Advantages of Exception Handling Result in code that has few errors.
S.SANTHI PRIYA UNIT 1 NOTES 17

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Easy to understand code. Less Expensive. More Quality. Increase speed of processing

Q9)PARAMETER PASSING METHODS


Passing Objects to Functions Objects may be passed to functions in just the same way that any other type of variable can. Objects are passed to functions through the use of the standard call-by-value mechanism. This means that a copy of an object is made when it is passed to a function. ie. another object is created. This raises the question of whether the object's constructor function is executed when the copy is made and whether the destructor function is executed when the copy is destroyed. Returning Objects A function may return an object to the caller. When an object is returned by a function, a temporary object is automatically created that holds the return value. It is this object that is actually returned by the function. After the value has been returned, this object is destroyed. The destruction of this temporary object may cause unexpected side effects in some situations.

S.SANTHI PRIYA

UNIT 1 NOTES

18

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

// Example Program for Returning objects from a function. #include<iostream.h> class myclass { int i; public: void seti (int n) {i=n;} int geti () {return i;} }; myclass f(); // return object of type myclass void main() { myclass o; o = f(); cout << o.geti() << "\n"; } myclass f() { myclass x; x.seti(1); return x; } Object Assignment Assuming that both objects are of the same type, you can assign one object to another.
S.SANTHI PRIYA UNIT 1 NOTES 19

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

This causes the data of the object on the right side to be copied into the data of the object on the left. // Example program Assigning objects #include <iostream.h> class myclass { int i; public: void seti(int n) { i=n; } int geti() { return i; } }; void main() { myclass ob1, ob2; ob1.seti(99); ob2 = ob1; // assign data from ob1 to ob2 cout << "This is ob2's i: " << ob2.geti(); } Arrays of Objects Object array is exactly the same as it is for any other type of array Example Program: #include <iostream.h> class cl { int i; public:
S.SANTHI PRIYA UNIT 1 NOTES 20

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

void seti(int j) { i=j; } int geti() { return i; } }; void main() { cl ob[3]; int i; for(i=0; ob[i].seti(i+1); for(i=0; i<3; i++) cout << ob[i].geti() << "\n"; } i<3; i++)

Q10) Polymorphism
Polymorphism means the ability to take more than one form. An operation may exhibit different instances. Polymorphism is the quality that allows one name to be used for two or more related but technically different purposes.

Polymorphism means the ability to take more than one form

S.SANTHI PRIYA

UNIT 1 NOTES

21

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Polymorphism

Compile time polymorphism Function overloading Operator overloading

run time polymorphism Virtual functions

Function overloading: In C++ it is possible to use one function name for many different purposes. This type of polymorphism is called function overloading. Two or more functions can have the same name as long as either the type of their arguments differs or the number of their arguments differs - or both. When two or more functions have the same name, they are said overloaded. Overloaded functions can help reduce the complexity of a program by allowing related operations to be referred to by the same name. The compiler will automatically select the correct function based upon the number and/or type of the arguments used to call the function. The following example illustrates the overloading of the absolute value function: #include < iostream > int abs (int n); long abs (long n); double abs (double n); int main( ) { cout<< "Abs value of -10: "<< abs(-10)<< "\n"; cout<< "Abs value of -10L: "<< abs(-10L)<< "\n"; cout<<"Abs value of -10.01:"<<abs(-10.01)<<"\n";
S.SANTHI PRIYA UNIT 1 NOTES 22

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

} int abs (int n) { cout << "In integer abs( )\n"; return n<0 ? -n : n; } long abs (long n) { cout << "In long abs( )\n"; return n<0 ? -n : n; } double abs (double n) { cout << "In double abs( )\n"; return n<0 ? -n : n; } Operator Overloading: When an operator is overloaded, that To operator loses none of its original meaning. Instead, it gains additional meaning relative to the class for which it is defined. overload an operator, you create an operator function. There are two important restrictions to remember when you are overloading an operator The precedence of the operator cannot be change. The number of operands that an operator takes cannot be altered.

Most C++ operators can be overloaded.We can give several meaning to an operator, depending upon the types of arguments used. This capability to overload an operator is called operator overloading. Operators are overloaded by creating operator functions. An operator function consists of a function definition, similar to a normal function except that the function name now becomes the keyword OPERATOR followed by the symbol being overloaded.
S.SANTHI PRIYA UNIT 1 NOTES 23

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

The general form or syntax of an operator function is Return type class name:: operator <operator symbol> (argument list) { //Body of the function }

Example Program: #include<iostream.h> #include<conio.h> class sample { int x,y,z; public: sample(int a,int b,int c) { x=a; y=b; z=c; } void operator -() { x=-x;
S.SANTHI PRIYA UNIT 1 NOTES 24

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

y=-y; z=-z; } void display() { cout<<"\t"<<x<<y<<z; } }; void main() { clrscr(); sample s(10,-20,30); cout<<"\n s is "; s.display(); -s; cout<<"\n-s is s.display(); getch(); } Virtual Functions: Virtual means existing in effect but not in reality. A virtual function is one that does not really exist but nevertheless appears real to some parts of program. Virtual functions provide a way for a program to decide, when it is running, what function to call. Virtual
S.SANTHI PRIYA UNIT 1 NOTES 25

";

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

function allows greater flexibility in performing the same kinds of action, on different kind of objects. While using virtual functions: It should be a member function of a class. Static member functions cannot be virtual functions. A virtual function should be declared in the base class specifications. A virtual function may or may not have function body. Virtual functions can be overloaded. Constructors cannot be declared as virtual functions. There can be virtual destructors #include<iostream.h> class base { public : virtual void display() { cout<<\n Display Base; } }; class derived : public base { public : void display() { cout<<\n Display Derived; } }; void main() { base b; derived d; base *bptr; bptr=&b; bptr->display();
S.SANTHI PRIYA UNIT 1 NOTES 26

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

bptr=&d; bptr->display(); }

Q11) Inheritance
A class have specified data type and if you need another data type similar to the previous one with some additional features, instead of creating a new data type++ allows to inherit the members of the existing type and can add some more features to the new class. This property is referred to as inheritance. The old class is called as base class and new class is called as derived class or child class. Inheritance is the process by which one object can acquire the properties of another. An object can inherit a general set of properties to which it can add those features that are specific only to itself. Inheritance is important because it allows an object to support the concept of hierarchical classification. Most information is made manageable by hierarchical classification. The child class inherits all those qualities associated with the parent and adds to them its own defining characteristics The general form or the syntax of specifying a derived class is: Class derivedclassname: acessspecifies baseclassname { //body of the derived class } The colon indicates that, the derived class named derivedclassname is derived from the base class named baseclassname.The access specifier of the base class must be either
S.SANTHI PRIYA UNIT 1 NOTES 27

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

private, protected or public. if no accessspecifier is present is assumed private by default. The body of the derived class contains member data and member functions of its own. We can summarize the different access types according to who can access them in the following way: Access public protected private members of the same class yes yes yes members of derived yes yes no classes not members yes no no Single inheritance: A derived class with only one base class is called as single Inheritance. The derived class can access all the members of the base class and can add members of its own. Single Inheritance
Student

Test

Multilevel inheritance: A derived class with another derived class is called as multilevel Inheritance.

MULTI LEVEL INHERITANCE


Student

Test

S.SANTHI PRIYA

UNIT 1 NOTES

28

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++ Result

Multiple inheritance: A derived class has many base classes is called as multiple Inheritance. Multiple Inheritance
TEST SPORTS

RESULT

Hierarchial inheritance: A base class has many derived classes is called as hierarchial Inheritance. Hierarchial Inheritance

ENGG

CSE

ECE

CSIT

Hybrid inheritance: join of any two type of inheritance. HYBRID INHERITANCE

S.SANTHI PRIYA

UNIT 1 NOTES

29

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++ STUDENT

SPORTS

TEST

OTHER

RESULT

Q12) Templates
A mechanism for writing routines that works for arbitrary ypes without knowing these types, i.e. type independent Most likely be seen in generic algorithm implementations, i.e. sorting & searching. Different Types of Templates Function Templates: SWAP and Insertion sort example Class Templates: Generic Memory Cell, Vector and Matrix class templates multiple parameter templates default template parameters typename keyword Function Templates: Function template: is a design or pattern for a function which allows processors to generate, (instantiation), an actual function from this design. template<class T>
S.SANTHI PRIYA UNIT 1 NOTES 30

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

T square(T a) { return (a*a) } void main() { T x,s; cout<<\n enter x value; cin>>x; s=square(x); cout<<\n square value is <<s; } Class Templates A class can be a template. Example: vector is a class template

#include<iostream.h> #include<conio.h> template<class T> class exam { T a,b; public: exam(T x,T y) { a=x; b=y; } void swap() { T c; c=a; a=b; b=c; } void display() { cout<<"\n a ="<<a;
S.SANTHI PRIYA UNIT 1 NOTES 31

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

cout<<"\n b ="<<b; } }; void main() { clrscr(); exam <int> ee(4,5); cout<<"\n a and b values before swaping"; ee.display(); ee.swap(); cout<<"\n a and b values after swaping"; ee.display(); getch(); exam <double> aa(4.1,5.8); cout<<"\n a and b values before swaping"; aa.display(); aa.swap(); cout<<"\n a and b values after swaping"; aa.display(); getch(); }

Q13)Algorithms,

performance

analysis-time

complexity and space complexity:


An algorithm is a set of instructions to be followed to solve a problem. There can be more than one solution (more than one algorithm) to solve a given problem. An algorithm can be implemented using different programming languages on different platforms. An algorithm must be correct. It should correctly solve the problem. Once we have a correct algorithm for a problem, we have to determine the efficiency of that algorithm. How much time that algorithm requires. How much space that algorithm requires.

Running time of an algorithm depends on Size of the input (sorting 100 int vs. 1000000 int) Speed, memoryetc of the computer
S.SANTHI PRIYA UNIT 1 NOTES 32

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Quality of the compiler (code optimization) The Execution Time of Algorithms Each operation in an algorithm (or a program) has a cost. Each operation takes certain of time. count = count + 1; A sequence of operations: count = count + 1; sum = sum + count; Cost: c1 Cost: c2 take a certain amount of time, but it is constant

Total Cost = c1 + c2 Example: Simple If-Statement Cost if (n < 0) absval = -n else absval = n; Total Cost <= c1 + max (c2, c3) General Rules for Estimation Loops: The running time of a loop is at most the running time of the statements inside of that loop times the number of iterations. Nested Loops: Running time of a nested loop containing a statement in the inner most loop is the running time of statement multiplied by the product of the sized of all loops. Consecutive Statements: Just add the running times of those consecutive statements. If/Else: Never more than the running time of the test plus the larger of running times of S1 and S2. What to Analyze c3 1 c1 c2 Times 1 1

S.SANTHI PRIYA

UNIT 1 NOTES

33

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

An algorithm can require different times to solve different problems of the same size. Ex. Searching an item in a list of n elements using sequential search. Cost: 1,2,...,n Worst-Case Analysis The maximum amount of time that an algorithm require to solve a problem of size n. This gives an upper bound for the time complexity of an algorithm. Normally, we try to find worst-case behavior of an algorithm. Best-Case Analysis The minimum amount of time that an algorithm require to solve a problem of size n. The best case behavior of an algorithm is NOT so useful. Average-Case Analysis The average amount of time that an algorithm require to solve a problem of size n. Sometimes, it is difficult to find the average-case behavior of an algorithm. We have to look at all possible data organizations of a given size n, and their distribution probabilities of these organizations. Worst-case analysis is more common than average-case analysis Algorithm Growth Rates We measure an algorithms time requirement as a function of the problem size. Problem size depends on the application: number of elements in a list for a sorting algorithm, the number disks for towers of hanoi. So, we say that (if the problem size is n) Algorithm A requires 5*n2 time units to solve a problem of size n. Algorithm A requires 7*n time units to solve a problem of size n. The most important thing to learn is how quickly the algorithms time requirement grows a function of the problem size. Algorithm A requires time proportional to n2. Algorithm A requires time proportional to n. An algorithms proportional time requirement is known as growth rate.
S.SANTHI PRIYA UNIT 1 NOTES 34

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

We can compare the efficiency of two algorithms by comparing their growth rates.

Q14) Order-of-Magnitude Analysis and Big 0 Notation:


If Algorithm A requires time proportional to f(n), Algorithm A is said to be order f(n), and it is denoted as O(f(n)). The function f(n) is called the algorithms growth-rate function. Since the capital O is used in the notation, this notation is called the Big O notation. If Algorithm A requires time proportional to n2, it is O(n2). If Algorithm A requires time proportional to n, it is O(n). If an algorithm requires n23*n+10 seconds to solve a problem size n. If constants k and n0 exist such that k*n2 > n23*n+10 for all n n0 . for all n 2 .
35

the algorithm is order n2 (In fact, k is 3 and n0 is 2) 3*n2 > n23*n+10


S.SANTHI PRIYA

UNIT 1 NOTES

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Thus, the algorithm requires no more than k*n2 time units for n n0 , So it is O(n2)

Growth-Rate Functions O(1) size. O(log2n) slowly as the problem size increases. O(n) O(n*log2n) than a linear algorithm. O(n2) with the
S.SANTHI PRIYA UNIT 1 NOTES 36

Time requirement is constant, and it is independent of the problems Time requirement for a logarithmic algorithm increases increases

Time requirement for a linear algorithm increases directly with the size of the problem. Time requirement for a n*log2n algorithm increases more rapidly

Time requirement for a quadratic algorithm increases rapidly

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

size of the problem. O(n3) with the size of the problem than the time requirement for a quadratic algorithm. O(2n) As the size of the problem increases, the time requirement for an Exponential algorithm increases too rapidly to be practical. If an algorithm takes 1 second to run with the problem size 8, what is the time requirement (approximately) for that algorithm with the problem size 16? If its order is: O (1) O (log2n) O (n) T (n) = 1 second T (n) = (1*log216) / log28 = 4/3 seconds T (n) = (1*16) / 8 = 2 seconds Time requirement for a cubic algorithm increases more rapidly

O (n*log2n) T (n) = (1*16*log216) / 8*log28 = 8/3 seconds O (n2) O (n3) O (2n) T (n) = (1*162) / 82 = 4 seconds T (n) = (1*163) / 83 = 8 seconds T (n) = (1*216) / 28 = 28 seconds = 256 seconds

Q15) Big-Omega Notation


o f(N) = (g(N)) o There are positive constants c and n0 such that o f(N) c g(N) when N n0 The growth rate of f(N) is greater than or equal to the growth rate of g(N). o Let f(N) = 2N2. Then o f(N) = (N) o f(N) = (N2) Big-Theta Notation : f(N) = (g(N)) iff
S.SANTHI PRIYA UNIT 1 NOTES 37

(best answer)

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

f(N) = O(g(N)) and f(N) = (g(N)) The growth rate of f(N) equals the growth rate of g(N) Example: Let f(N)=N2 , g(N)=2N2 o We write f(N) = O(g(N)) and f(N) = (g(N)), thus f(N) = (g(N)). Notations Asymptotically less than or equal to Asymptotically greater than or equal to Asymptotically equal to Asymptotically strictly less O o (Big-Oh) (Big-Omega) (Big-Theta) (Little-Oh)

Q16) List ADT:


AbstractDataType LinearList {
S.SANTHI PRIYA UNIT 1 NOTES 38

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Instances ordered finite collections of zero or more elements Operations isEmpty(): return true iff the list is empty, false otherwise size (): return the list size (i.e., number of elements in the list) get(index): return the indexth element of the list indexO f(x): return the index of the first occurrence of x in he list, return -1 if x is not in the list remove(index): remove and return the indexth element, elements with higher index have their index reduced by 1 add(theIndex, x): insert x as the indexth element, elements ith theIndex >= index have their index increased by 1 output(): output the list elements from left to right }

Each node contains the element and a pointer to a structure containing its successor the last cells next link points to NULL Compared to the array implementation, the pointer implementation uses only as much space as is needed for the elements currently on the list but requires space for the pointers in each cell linked list is a series of connected nodes Each node contains at least A piece of data (any type) Pointer to the next node in the list Head: pointer to the first node The last node points to NULL
S.SANTHI PRIYA UNIT 1 NOTES 39

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Q17) Binary search Trees


Binary search tree Every element has a unique key. The keys in a nonempty left subtree (right subtree) are smaller (larger) than the key in the root of subtree. The left and right subtrees are also binary search trees. Binary Search Trees (BST) are a type of Binary Trees with a special organization of data. This data organization leads to O(log n) complexity for searches, insertions and deletions in certain types of the BST (balanced trees).O(h) in general Binary Search algorithm of an array of sorted items reduces the search space by one half after each comparison

34 0

41 1

56 63 2 3

72 89 4 5

95 6

34 0

41 1

56 2

72 4 72 4

89 5

95 6 95 6

34 0

56 2

S.SANTHI PRIYA

UNIT 1 NOTES

40

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Organization Rule for BST


the values in all nodes in the left subtree of a node are less than the node value the values in all nodes in the right subtree of a node are greater than the node values

63

4 1

8 9

34

56

72

95

template<class T> Class binarysearchtree { Public: const T &findmin(); const T &findmax(); const T &find(const &x); bool isemplty(); void insert(const T &x); void remove(const T &x) }; Find minimum value Binarysearchtree<T> :: findmin(Binarynode<T> *t)
S.SANTHI PRIYA UNIT 1 NOTES 41

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

{ If(t==NULL) return NULL; If(t->left==NULL) return t; return findmin(t->left); } Find maximum(non recursive) template<class T> Binarysearchtree<T> :: findmax(Binarynode<T> *t) { if(t!=NULL) while(t->right!=NULL) t=t->right; return t; } Search in BST Binarysearchtree<T> :: find(T &x,Binarynode<T> *t) { If(t==NULL) return NULL; elseIf(x<t->element) return find(x,t->left); elseIf(x>t->element) return find(x,t->right); else return t; } Insertion
S.SANTHI PRIYA UNIT 1 NOTES 42

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Binarysearchtree<T> :: insert(T &x,Binarynode<T> *t) { If(t==NULL) t=new Binarynode(x,NULL,NULL); elseIf(x<t->element) insert(x,t->left); elseIf(x>t->element) insert(x,t->right); else ; } Deletion Binarysearchtree<T> :: remove(T &x, Binarynode<T> *t) { If(t==NULL) return; If(x<t->element) remove(x,t->left); elseIf(x>t->element) remove(x,t->right); elseif(t->left!=NULL && t->right!=NULL) { else { Binarynode<T> *oldnode =t; t=(t->left!=NULL)?t->left;t->right; delete oldnode; } }
S.SANTHI PRIYA UNIT 1 NOTES 43

t->element=findmin(t->right)->element; remove(x,t->right); }

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Q18) AVL-Trees
The disadvantage of a binary search tree is that its height can be as large as N-1.This means that the time needed to perform insertion and deletion and many other operations can be O(N) in the worst case. We want a tree with small height. A binary tree with N node has height at least (log N) .Thus, our goal is to keep the height of a binary search tree O(log N).Such trees are called balanced binary search trees. Examples are AVL tree, red-black tree Height of a node The height of a leaf is 1. The height of a null pointer is zero.The height of an internal node is the maximum height of its children plus 1. An AVL tree is a binary search tree in which for every node in the tree, the height of the left and right subtrees differ by at most 1.

Let x be the root of an AVL tree of height h Let Nh denote the minimum number of nodes in an AVL tree of height h Operations (searching, insertion, deletion) on an AVL tree will take O(log N) time. Rotations When the tree structure changes (e.g., insertion or deletion), we need to transform the tree to restore the AVL tree property.This is done using single rotations or double rotations.
S.SANTHI PRIYA UNIT 1 NOTES 44

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Single Rotation The new key is inserted in the subtree A. The AVL-property is violated at x height of left(x) is h+2 height of right(x) is h.

The new key is inserted in the subtree C. The AVL-property is violated at x.

S.SANTHI PRIYA

UNIT 1 NOTES

45

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

AVL Tree

x
8

8
4 0.8 1

y
4

A Insert 0.8

3 5
4 8

After rotation

0.8

Double rotation The new key is inserted in the subtree B1 or B2. The AVL-property is violated at x. x-y-z forms a zig-zag shape

S.SANTHI PRIYA

UNIT 1 NOTES

46

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

The new key is inserted in the subtree B1 or B2. The AVL-property is violated at x.

AVL Tree
3

x
8

y 8
4

B 4 5
3.5 8

3.5

Insert 3.5

After Rotation

Q19) Red Black Trees


Colored Nodes Definition Binary search tree.
S.SANTHI PRIYA UNIT 1 NOTES 47

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Each node is colored red or black. Root and all external nodes are black. No root-to-external-node path has two consecutive red nodes. All root-to-external-node paths have the same number of black nodes Colored Edges Definition Binary search tree. Child pointers are colored red or black. Pointer to an external node is black. No root to external node path has two consecutive red pointers. Every root to external node path has the same number of black pointers.

10

7 3 8 30 35

40 45

20 25

60

The height of a red black tree that has n (internal) nodes is between log2(n+1) and 2log2(n+1). Start with a red black tree whose height is h; collapse all red nodes into their parent black nodes to get a tree whose node-degrees are between 2 and 4, height is >= h/2, and all external nodes are at the same level.

S.SANTHI PRIYA

UNIT 1 NOTES

48

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

10

7 3 8 30 35

40 45

20 25

60

Rb0 (case 1)

py v a b y a v b

py y

Color change. Now, py is root of deficient subtree. Continue!

S.SANTHI PRIYA

UNIT 1 NOTES

49

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Rb1 (case 1)

py v a b y a

v py b y

LL rotation. Deficiency eliminated. Done!


Rb0 (case 2)

py v a b y a v b

py y

Color change. Deficiency eliminated. Done!

S.SANTHI PRIYA

UNIT 1 NOTES

50

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Rb1 (case 2)

py v a b w c y a v b

w py c y

LR rotation. Deficiency eliminated. Done!

Q20) Splay Trees


Bottom-Up Splay Trees Top-Down Splay Trees Bottom-Up Splay Trees Search, insert, delete, and join are done as in an unbalanced binary search tree. Search, insert, and delete are followed by a splay operation that begins at a splay node. When the splay operation completes, the splay node has become the tree root. Join requires no splay (or, a null splay is done). For the split operation, the splay is done in the middle (rather than end) of the operation. Splay Node search(k)

S.SANTHI PRIYA

UNIT 1 NOTES

51

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

2 0 10 6 2 8 15 25 30 40

If there is a pair whose key is k, the node containing this pair is the splay node. Otherwise, the parent of the external node where the search terminates is the splay node. Splay Node insert(newPair) If there is already a pair whose key is newPair.key, the node containing this pair is the splay node. Otherwise, the newly inserted node is the splay node. Splay Node delete(k) If there is a pair whose key is k, the parent of the node that is physically deleted from the tree is the splay node. Otherwise, the parent of the external node where the search terminates is the splay node. Splay Node split(k) Use the unbalanced binary search tree insert algorithm to insert a new pair whose key is k. The splay node is as for the splay tree insert algorithm. Following the splay, the left subtree of the root is S, and the right subtree is B. Splay Step If q = null or q is the root, do nothing (splay is over). If q is at level 2, do a one-level move and terminate the splay operation. Top-Down Splay Trees
S.SANTHI PRIYA UNIT 1 NOTES 52

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

On the way down the tree, split the tree into the binary search trees S (small elements) and B (big elements). Similar to split operation in an unbalanced binary search tree. However, a rotation is done whenever an LL or RR move is made. Move down 2 levels at a time, except (possibly) in the end when a one level move is made. When the splay node is reached, S, B, and the subtree rooted at the splay node are combined into a single binary search tree.

Q21) B TREES
Large degree B-trees used to represent very large dictionaries that reside on disk. Smaller degree B-trees used for internal-memory dictionaries to overcome cachemiss penalties. Definition assumes external nodes (extended m-way search tree). B-tree of order m. m-way search tree. Not empty => root has at least 2 children. Remaining internal nodes (if any) have at least ceil(m/2) children. External (or failure) nodes on same level. 2-3 And 2-3-4 Trees B-tree of order m. m-way search tree. Not empty => root has at least 2 children. Remaining internal nodes (if any) have at least ceil(m/2) children. External (or failure) nodes on same level. 2-3 tree is B-tree of order 3. 2-3-4 tree is B-tree of order 4. Worst-case search time. (time to fetch a node + time to search node) * height
S.SANTHI PRIYA UNIT 1 NOTES 53

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

(a + b*m + c * log2m) * h where a, b and c are constants.

Insert

8 4

15 20 5 6 9 16 17 30 40

1 3

Insertion into a full leaf triggers bottom-up node splitting pass.

Analysis of worst-case and average number of disk accesses for an insert. Delete and analysis. Structure for B-tree node DELETE Deletion from interior node is transformed into a deletion from a leaf node. Deficient leaf triggers bottom-up borrowing and node combining pass. Deficient node is combined with an adjacent sibling who has exactly ceil(m/2) 1 pairs. After combining, the node has [ceil(m/2) 2] (original pairs) + [ceil(m/2) 1] (sibling pairs) + 1 (from parent) <= m 1 pairs. Cache access time vs main memory access time. Reduce main memory accesses using a B-tree.
S.SANTHI PRIYA UNIT 1 NOTES 54

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Node Structure q a0 p1 a1 p2 a2 pq aq Complexity Of B-Tree Node Operations Search a B-tree node O(log m). Find middle pair O(log m). Insert a pair O(log m). Delete a pair O(log m). Split a B-tree node O(log m). Join 2 B-tree nodes O(m). Need to copy indexed red-black tree that represents one B-tree node into the array space of the other B-tree node.

Q22) Divide And Conquer


Distinguish between small and large instances. Small instances solved differently from large ones. Small instance. Sort a list that has n <= 10 elements. Find the minimum of n <= 2 elements. Large instance. Sort a list that has n > 10 elements. Find the minimum of n > 2 elements. Solving A Small Instance small instance is solved using some direct/simple strategy. Sort a list that has n <= 10 elements. Use count, insertion, bubble, or selection sort. Find the minimum of n <= 2 elements. When n = 0, there is no minimum element. When n = 1, the single element is the minimum.

S.SANTHI PRIYA

UNIT 1 NOTES

55

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

When n = 2, compare the two elements and determine which is smaller. Solving A Large Instance A large instance is solved as follows: Divide the large instance into k >= 2 smaller instances. Solve the smaller instances somehow. Combine the results of the smaller instances to obtain the result for the original large instance. Sort a list that has n > 10 elements. Sort 15 elements by dividing them into 2 smaller lists. One list has 7 elements and the other has 8. Sort these two lists using the method for small lists. Merge the two sorted lists into a single sorted list. Recursion In Divide And Conquer Often the smaller instances that result from the divide step are instances of the original problem (true for our sort and min problems). In this case, If the new instance is a small instance, it is solved using the method for small instances. If the new instance is a large instance, it is solved using the divide-andconquer method recursively. Generally, performance is best when the smaller instances that result from the divide step are of approximately the same size

Q23) Merge Sort


k=2 First ceil(n/2) elements define one of the smaller instances; remaining floor(n/2) elements define the second smaller instance. Each of the two smaller instances is sorted recursively. The sorted smaller instances are combined using a process called merge. Complexity is O(n log n).
S.SANTHI PRIYA UNIT 1 NOTES 56

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Usually implemented nonrecursively

Merge Sort
[8, 3, 13, 6, 2, 14, 5, 9, 10, 1, 7, 12, 4] [8, 3, 13, 6, 2, 14, 5] [8, 3, 13, 6] [2, 14, 5] [9, 10, 1, 7, 12, 4] [9, 10, 1] [7, 12, 4] [7, 12] [4] [7] [12]

[8, 3] [13, 6] [2, 14] [5] [9, 10] [1] [8] [3] [13] [6] [2] [14] [9] [10]
Time Complexity Let t(n) be the time required to sort n elements. t(0) = t(1) = c, where c is a constant. When n > 1, t(n) = t(ceil(n/2)) + t(floor(n/2)) + dn, where d is a constant.

To solve the recurrence, assume n is a power of 2 and use repeated substitution. t(n) = O(n log n).

Q24) Quick Sort


Small instance has n <= 1. Every small instance is a sorted instance. To sort a large instance, select a pivot element from out of the n elements. Partition the n elements into 3 groups left, middle and right. The middle group contains only the pivot element. All elements in the left group are <= pivot. All elements in the right group are >= pivot. Sort left and right groups recursively.
S.SANTHI PRIYA UNIT 1 NOTES 57

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Pivot is leftmost element in list that is to be sorted. When sorting a[6:20], use a[6] as the pivot. Text implementation does this. Randomly select one of the elements to be sorted as the pivot. When sorting a[6:20], generate a random number r in the range [6, 20]. Use a[r] as the pivot. Median-of-Three rule. From the leftmost, middle, and rightmost elements of the list to be sorted, select the one with median key as the pivot. When sorting a[6:20], examine a[6], a[13] ((6+20)/2), and a[20]. Select the element with median (i.e., middle) key. If a[6].key = 30, a[13].key = 2, and a[20].key = 10, a[20] becomes the pivot. If a[6].key = 3, a[13].key = 2, and a[20].key = 10, a[6] becomes the pivot. Complexity O(n) time to partition an array of n elements. Let t(n) be the time needed to sort n elements. t(0) = t(1) = c, where c is a constant. When t > 1, t(n) = t(|left|) + t(|right|) + dn, where d is a constant. t(n) is maximum when either |left| = 0 or |right| = 0 following each partitioning.

Q25) Sparse Matrices


sparse many elements are zero Example Of Sparse Matrices 1. diagonal 2. tridiagonal Representation Of Unstructured Sparse Matrices Single linear list in row-major order.scan the nonzero elements of the sparse matrix in row-major order.each nonzero element is represented by a triple (row, column, value)
S.SANTHI PRIYA UNIT 1 NOTES 58

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

the list of triples may be an array list or a linked list (chain) Single Linear List Example 00304 00570 00000 02600 list = row value 1 1 2 2 4 4 3 4 5 7 2 6 Array Linear List Representation row list = value 1 1 2 2 4 4 3 4 5 7 2 6 element row column value Node structure. 0 1 2 3 4 5 1 1 2 2 4 4 3 5 3 4 2 3 3 4 5 7 2 6 column 3 5 3 4 2 3 column 3 5 3 4 2 3

row value
row list = column value

col next
1 1 2 2 4 4 3 5 3 4 2 3 3 4 5 7 2 6

1 3 3

1 5 4

2 3 5

2 4 7

4 2 2

4 3 6 null

firstNode
S.SANTHI PRIYA UNIT 1 NOTES 59

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Array Of Row Chains


null 3 3 5 null 3 5 4 7 4

00304 00570 00000 02600

null

null 2 row[] 2 3 6

Orthogonal List Representation

row down

col next

value

S.SANTHI PRIYA

UNIT 1 NOTES

60

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Row Lists

00304 00570 00000 02600

1 3 3

1 5 4 n 2 4 7 n

2 3 5

null

4 2 2

4 3 6 n

S.SANTHI PRIYA

UNIT 1 NOTES

61

ADVANCED DATA STRUCTURES AND ALGORITHMS USING C++

Orthogonal Lists

00304 00570 00000 02600

1 3 3

1 5 4 n n 2 4 7 n

2 3 5

null

4 2 2 n row[]

4 3 6 n n

S.SANTHI PRIYA

UNIT 1 NOTES

62

Você também pode gostar