Docsity

Data structure notes updated, Exercises of Computer Science

Partial preview of the text

Download Data structure notes updated and more Exercises Computer Science in PDF only on Docsity!

Algorithms and Data Structure 1

Biyani's Think Tank

Concept based notes

Data Structure and Algorithms

(BCA Part-I)

Bhavana Sangamnerkar

M.Sc. (Comp. Prog.), PGDCA

H.O.D.

Revised by: Neha jain Revised by: Ms Rashmi Sharma

Information Technology
Biyani Girls College, Jaipur

2

Published by :

Think Tanks
Biyani Group of Colleges

Concept & Copyright :

Biyani Shikshan Samiti

Sector-3, Vidhyadhar Nagar, Jaipur-302 023 (Rajasthan) Ph : 0141-2338371, 2338591-95 Fax : 0141- E-mail : [email protected] Website :www.gurukpo.com; www.biyanicolleges.org

ISBN : 978-93-81254-40-

Edition : 2011 Price :

Leaser Type Setted by : Biyani College Printing Department

While every effort is taken to avoid errors or omissions in this Publication, any mistake or omission that may have crept in is not intentional. It may be taken note of that neither the publisher nor the author will be responsible for any damage or loss of any kind arising to anyone in any manner on account of such errors and omissions.

4

Syllabus B.C.A. Part-I

Algorithms and Data Structure

Algorithms , Pseudo Code, Efficiency of Algorithms, Analyzing Algorithms and Problems, Complexity Measures, Basic Time Analysis of an Algorithm, Space Complexity.

Data Abstraction and Basic Data Structures, Data Types, Abstract Data Types and C++ Classes.

String Processing (Storing Strings, String Operations, Word Processing, Pattern Matching Algorithms).

Arrays and their Representation, Representation of Linear Arrays in Memory, Sorting and Searching, Bubble Sort and Binary Search, Multidimensional Arrays, Pointer Arrays, Records and Record Structures.

Linked Lists , Representation of Linked List in Memory, Insertion, Deletion and Searching of Linked List, Two Way Lists, Stacks, Array Representation of Stacks, Arithmetic Expressions, Polish Notations, Quick Sort, Recursion, Queues, De - queues, Priority Queues.

Tables and Searching, Linear Search, Binary Search, Hash Tables, Trees, Binary and N-ary Trees, Representation of Binary Trees in Memory, Traversing Binary Trees, Traversal Algorithms using Stacks, Header Nodes, Threads, Binary Search Trees, Heap, Heapsort, Huffman‘s Algorithm.

Graph and their Representation, Sequential Representation, Warshall‘s Algorithm, Linked Representation of Graphs, Operations on Graphs Traversing a Graph.

Sorting and Searching : Sequential, Binary and Hashed Searching, Internal and External Sorting Techniques, Bubble Sort, Insertion Sort, Selection Sort, Merge Sort, Radix Sort and Quick Sort Comparison.

Algorithms and Data Structure 5

Content

S.No. Name of Topic

**1. Basics of Algorithms

  1. Data Structure Organisation
  2. Arrays
  3. Strings
  4. C++ : Classes and Objects
  5. Linked List
  6. Stacks
  7. Queue
  8. Sorting and Searching Techniques
  9. Graph
  10. Tree

13.**

Unsolved Papers 2011 to 2006 MCQ

Algorithms and Data Structure 7

(4) Test A Program : Testing a program consists of 2 phases : debugging and performance management. Debugging is the process of executing programs on sample data sets to determine whether results are incorrect if so corrects them. Performance management is the process of executing a correct program on data sets and measuring the time and space it takes to compute the results. These timing figures are useful in that they may confirm a previously done analysis and point out logical places to perform useful optimization.

Q.2. Define Algorithms with suitable example.

Ans.: Consider the following three examples. What do they all have in common?

How to change your motor oil (1) Place the oil pan underneath the oil plug of your car. (2) Unscrew the oil plug. (3) Drain oil. (4) Replace the oil plug. (5) Remove the oil cap from the engine. (6) Pour in 4 quarts of oil. (7) Replace the oil cap. Therefore an algorithm is a set of instructions for solving a problem. Once we have created an algorithm, we no longer need to think about the principles on which the algorithm is based. This means that algorithms are a way of capturing intelligence and sharing it with others. Once you have encoded the necessary intelligence to solve a problem in an algorithm, many people can use your algorithm without needing to become experts in a particular field.

Q.3 Why the algorithm are important to computers. How can we create it in understandable form?

Ans. Algorithms are especially important to computers because computers are really general purpose machines for solving problems. But in order for a computer to be useful, we must give it a problem to solve and a technique for

8

solving the problem. Through the use of algorithms, we can make computers "intelligent" by programming them with various algorithms to solve problems. Because of their speed and accuracy, computers are well-suited for solving tedious problems such as searching for a name in a large telephone directory or adding a long column of numbers. However, the usefulness of computers as problem solving machines is limited because the solutions to some problems cannot be stated in an algorithm. Much of the study of computer science is dedicated to discovering efficient algorithms and representing them so that they can be understood by computers. An informal definition of an algorithm is "a set of instructions for solving a problem" and we illustrated this definition with a recipe, and instructions for changing the oil in a car engine. You also created your own algorithm for putting letters and numbers in order. While these simple algorithms are fine for us, they are much too ambiguous for a computer. In order for an algorithm to be applicable to a computer, it must have certain characteristics. We will specify these characteristics in our formal definition of an algorithm. An algorithm is a well-ordered collection of unambiguous and effectively computable operations that when executed produces a result and halts in a finite amount of time [Schneider and Gersting 1995]. With this definition, we can identify five important characteristics of algorithms : Algorithms are well-ordered. Algorithms have unambiguous operations. Algorithms have effectively computable operations. Algorithms produce a result. Algorithms halt in a finite amount of time.

When writing algorithms, we have several choices of how we will specify the operations in our algorithm. One option is to write the algorithm using plain English. Although plain English may seem like a good way to write an algorithm, it has some problems that make it a poor choice. First, plain English is too wordy. When we write in plain English, we must include many words

10

each other. We can easily see the advantage of this organization by comparing the structured English algorithm with the plain English algorithm. How to change your motor oil Plain English Structured English First, place the oil pan underneath the oil plug of your car. Next, unscrew the oil plug and drain the oil. Now, replace the oil plug. Once the old oil is drained, remove the oil cap from the engine and pour in 4 quarts of oil. Finally, replace the oil cap on the engine.

  1. Place the oil pan underneath the oil plug of your car.
  2. Unscrew the oil plug.
  3. Drain oil.
  4. Replace the oil plug.
  5. Remove the oil cap from the engine.
  6. Pour in 4 quarts of oil.
  7. Replace the oil cap. For the remainder of this study, we will write our algorithms using the structured English approach.

Q.4. How can we analyse an Algorithm?

Ans.: To analyze an algorithm is to determine the amount of resources (such as time

and storage) necessary to execute it. Most algorithms are designed to work with inputs of arbitrary length. Usually the efficiency or complexity of an algorithm is stated as a function relating the input length to the number of steps ( time complexity ) or storage locations ( space complexity ). Algorithm analysis is an important part of a broader computational complexity theory, which provides theoretical estimates for the resources needed by any algorithm which solves a given computational problem. These estimates provide an insight into reasonable directions of search of efficient algorithms.

Q.5. Explain Analysis of Algorithm in terms of different Order Notations.

Algorithms and Data Structure 11

Ans.: In theoretical analysis of algorithms it is common to estimate their complexity in asymptotic sense , i.e., to estimate the complexity function for reasonably large length of input. Big O notation, omega notation and theta notation are used to this end. For instance, binary search is said to run an amount of steps proportional to a logarithm, or in O(log(n)), colloquially "in logarithmic time". Usually asymptotic estimates are used because different implementations of the same algorithm may differ in efficiency. However the efficiencies of any two "reasonable" implementations of a given algorithm are related by a constant multiplicative factor called hidden constant. Asymptotic Notation : If we want to treat large problems (these are the critical ones), we are interested in the asymptotic behavior of the growth of the running time function. Thus, when comparing the running times of two algorithms : Constant factors can be ignored. Lower order terms are unimportant when the higher order terms are different. For instance, when we analyze selection sort, we find that it takes T(n) = n2 + 3n - 4 array accesses.

For large values of n, the 3n - 4 part is insignificant compared to the n^2 part.

An algorithm that takes a time of 100n^2 will still be faster than an algorithm that n^3 for any value of n larger than 100. Asymptotically Tight Upper and Lower Bound : Big-Theta "Θ"-Notation :

Definition : Let f(n) and g(n) be real-valued functions of a single non- negative integer argument. We write f(n) = Θ(g(n)) if there exist positive real-valued constants c 1 , c 2 and a positive integer n 0 such that : 0 ≤ c 1 g(n) ≤ f(n) ≤ c 2 g(n) for all n ≥ n 0. In other words : For large inputs (asymptotically) f(n) is "sandwiched" between c 1 g(n) and c 2 g(n). Examples :

Algorithms and Data Structure 13

Definition : Let f(n) and g(n) be real-valued functions of a single non- negative integer argument. We write f(n) = Ω(g(n)) if there exist a positive real-valued constant c and a positive integer n 0 such that : 0 ≤ c g(n) ≤ f(n) for all n ≥ n 0. In other words : For large inputs (asymptotically) f(n) is above c g(n). Note : We have f(n) = Θ(g(n)) iff (if and only if) f(n) = O(g(n)) and f(n) = Ω(g(n)). In other words : If f(n) is &#x0398(g(n)), the f(n) is &#x03A9(g(n)). If f(n) is &#x0398(g(n)), then f(n) is O(g(n)). Example : 2n 3 +3n is &#x03A9(n^3 ).

Asymptotically Non-Tight Upper Bound : Little-oh "o"-Notation : Definition : Let f(n) and g(n) be real-valued functions of a single non- negative integer argument. We write f(n) = o(g(n)) if for any positive real-valued constant c exists a positive integer n 0 such that : 0 ≤ f(n) ≤ c g(n) for all n ≥ n 0. In other words, the inequality holds for all constants c. For any constant c we can come up with large enough inputs n so that f(n) is below c g(n). g(n) grows a lot faster than f(n) : f(n)/g(n)→0 as n→∞. Example : log(n) is o(n) Asymptotically Non-Tight Lower Bound: Little-Omega "ω" Notation

14

Definition : Let f(n) and g(n) be real-valued functions of a single non- negative integer argument. We write f(n) = ω(g(n)) if for any positive real-valued constant c exists a positive integer n 0 such that : 0 ≤ c g(n) ≤ f(n) for all n ≥ n 0. As an alternative definition we can say the following : Definition : Let f(n) and g(n) be real valued functions of an integer variable. We say f(n) is ω(g(n)) if g(n) is o(f(n)). This is pronounced as "f(n) is little-omega of g(n)". f(n) grows a lot faster than f(n) : f(n)/g(n)→∞ as n→∞. Example : n^2 is ω(nlog(n)).

Q.6. Define Efficiency of an Algorithm in terms of Time and Space.

Ans.: Efficiency of an algorithm : In computer science, efficiency is used to describe properties of an algorithm relating to how much of various types of resources it consumes. The two most frequently encountered are speed or running time, the time it takes for an algorithm to complete, and space, the memory or non-volatile storage used by the algorithm during its operation. Optimization is the process of making code as efficient as possible, sometimes focusing on space at the cost of speed, or vice versa. The speed of an algorithm is measured in various ways. The most common method uses time complexity to determine the Big-O of an algorithm: often, it is possible to make an algorithm faster at the expense of space. This is the case whenever you cache the result of an expensive calculation rather than recalculating it on demand. This is a very common method of improving speed, so much so that languages often add special features to support it, such as C++'s mutable keyword. The space of an algorithm is actually two separate but related things. The first part is the space taken up by the compiled executable on disk (or equivalent, depending on the hardware and language) by the algorithm. This can often be reduced by preferring run-time decision making mechanisms (such as virtual functions and run-time type information) over certain compile-time decision

16

computation may be defined in terms of an abstract computer, e.g., Turing machine, and/or by postulating that certain operations are executed in unit time. For example, if the sorted set to which we apply binary search has N elements, and we can guarantee that a single binary lookup can be done in unit time, then at most log 2 N + 1 time units are needed to return an answer.

Exact measures of efficiency are useful to the people who actually implement and use algorithms, because they are more precise and thus enable them to know how much time they can expect to spend in execution. To some people (e.g. game programmers), a hidden constant can make all the difference between success and failure.

Time efficiency estimates depend on what we define to be a step. For the analysis to make sense, the time required to perform a step must be guaranteed to be bounded above by a constant. One must be careful here; for instance, some analyses count an addition of two numbers as a step. This assumption may not be warranted in certain contexts. For example, if the numbers involved in a computation may be arbitrarily large, addition no longer can be assumed to require constant time

Q.7. Compare the Performance of an Algorithm. Explain Algorithmic Complexity Measures.

Ans.: Our aim is to compare the performance of algorithms.

We can consider the average case or the worst case performance (referring to an instance of a given problem). Usually we treat only the worst case performance : The worst case occurs fairly often, example: looking for in entry in a database that is not present. The result of the worst case analysis is often not different to the average case analysis (same order of complexity). Running Times : One way to compare running times is simply to run several tests for each algorithm and compare the timings.

Algorithms and Data Structure 17

Another way is to estimate the time required for an algorithm to solve a problem. The result of the analysis of an algorithm is usually a formula giving the amount of machine operations (e.g., floating point operations, number of memory accesses, number of comparisons, etc ) or some other metric (e.g., number of elements to sort, neurons or connections in a neural network, vertices or edges in a tree, etc. ), that the algorithm takes to complete. In the following we write running times as a function of n. Space Complexity : Running time is usually the thing we care most about. But it can be as well important to analyze the amount of memory used by a program. If a program takes a lot of time, you can still run it, and just wait longer for the result. However if a program takes a lot of memory, you may not be able to run it at all, so this is an important parameter to understand. We analyze things differently for recursive and iterative programs. For an iterative program , it is usually just a matter of looking at the variable declarations and storage allocation calls, e.g., array of n numbers. Analysis of recursive program space is more complicated: the space used at any time is the total space used by all recursive calls active at that time. Each recursive call takes a constant amount of space: some space for local variables and function arguments, and also some space for remembering where each call should return to.

Q.8. What is Pseudo Code? Explain how can we use Pseudo Code to design a Program?

Ans.: Pseudo code is a short hand way of describing a computer program. Rather than use the specific syntax of a computer language, more general wording is used. Using pseudocode, it is easier for a non-programmer to understand the general workings of the program.

Pseudo code (pronounced SOO-doh-kohd) is a detailed yet readable description of what a computer program or algorithm must do, expressed in a

Algorithms and Data Structure 19

IF Management Approval is obtained THEN Allow loan facility ELSE Reject ENDIF ENDIF ELSE Reject ENDIF □ □ □

20

Chapter-

Data Structure Ogranisation

Q.1. Explain Data Types along with their sizes and ranges.

Ans.: Data Types : The type of a data object in C determines the range and kind of

values an object can represent, the size of machine storage reserved for an object, and the operations allowed on an object. Functions also have types, and the function's return type and parameter types can be specified in the function's declaration

Data Sizes : An object of a given data type is stored in a section of memory having a discreet size. Objects of different data types require different amounts of memory. Following table shows the size and range of the basic data types. Sizes and Ranges of Data Types :

Type Size Range Integral Types :

short int , or signed short int 16 bits - 32768 to 32767

unsigned short int 16 bits 0 to 65535

int or signed int 32 bits - 2147483648 to 2147483647

unsigned int 32 bits 0 to 4294967295

long int , or signed long int (OpenVMS) 32 bits^ -^2147483648 to 2147483647

long int , or signed long int (Digital UNIX)

64 bits -^ 9223372036854775808 to 9223372036854775807