Docsity

data structures and algorithms, Lecture notes of Data Structures and Algorithms

Toggle sidebar
bg1
Data Structures and Algorithms-course content.
Introduction to data structures and algorithms: definitions and uses of data structures and algorithms, role
of data structures and algorithms programming, choice of data structures and algorithms. Elementary data
structures: list, queue, stack, tree, records, arrays; types of list: linear-linked list, doubly linked list, circular
linked list, circular doubly linked list; types of queue: circular queue; types of trees: AVL tree, red black
trees, b-trees; graphs; array based and pointer-based implementation of data structures, hashing, heap,
linear, binary search algorithms; sorting algorithms; depth-first, breadth, hill-climbing, least-cost search
algorithms using either a structured programming language or an OOP language such as C++, JAVA, C#
1.0 Overview.
-Data representation in a program/ memory deals with the generalization of data in terms of type.
- A data type is a well-defined collection of data with a well-defined set of operations on it.
-Data type of a variable is the set of values that the variable may assume.
-A type is a set, and the elements of the set are called the value of the type. Examples: Type integer
represents the set of all integers; type real represents the set of all real numbers. i.e. in C int, double,
-Variable: - A variable is a named data storage location in your computer’s memory.
-Variable names are used in a program to refer to the data stored memory.
1.1 Definitions
What Are Data Structures and Algorithms?
We begin with a definition for “algorithm:
1.1.1 Algorithm - A finite sequence of steps for accomplishing some computational task. An algorithm must:
Have steps that are simple and definite enough to be done by a computer, and
Terminate after finitely many steps
Notice that an algorithm is a sequence of steps, not a program.
You might use the same algorithm in different programs, or express the same algorithm in different
languages, because an algorithm is an entity that is abstracted from implementation details.
1.1.2 Abstract data type (ADT) -:
Def 1: A set of values (the carrier set), and operations on those values.
Def 2: ADT is defined as a mathematical model with a collection of operations defined on that model.
-Abstract Data Type (ADT)-defines the type of data that can be stored in a structure, and the available
methods to operate on the data.
- Example. In Java, an ADT is modelled as an interface and implemented as a class.
- Classes specify how a given operation on the ADT's data is to be performed.
N.B: A Data Structure is an actual implementation of an ADT i.e. a translation of ADT into statements of a
programming language and consists of the following:
The declarations that define a variable to be of that ADT type.
The operations defined on the ADT (using procedures of the programming language).
1
DATA STRUCTURES AND ALGORITHMS
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33

Partial preview of the text

Download data structures and algorithms and more Lecture notes Data Structures and Algorithms in PDF only on Docsity!

Data Structures and Algorithms-course content. Introduction to data structures and algorithms: definitions and uses of data structures and algorithms, role of data structures and algorithms programming, choice of data structures and algorithms. Elementary data structures: list, queue, stack, tree, records, arrays; types of list: linear-linked list, doubly linked list, circular linked list, circular doubly linked list; types of queue: circular queue; types of trees: AVL tree, red black trees, b-trees; graphs; array based and pointer-based implementation of data structures, hashing, heap, linear, binary search algorithms; sorting algorithms; depth-first, breadth, hill-climbing, least-cost search algorithms using either a structured programming language or an OOP language such as C++, JAVA, C# 1.0 Overview.

- Data representation in a program/ memory deals with the generalization of data in terms of type. - A data type is a well-defined collection of data with a well-defined set of operations on it. - Data type of a variable is the set of values that the variable may assume. - A type is a set, and the elements of the set are called the value of the type. Examples: Type integer represents the set of all integers; type real represents the set of all real numbers. i.e. in C int, double, - Variable: - A variable is a named data storage location in your computer’s memory. - Variable names are used in a program to refer to the data stored memory. 1.1 Definitions What Are Data Structures and Algorithms? We begin with a definition for “algorithm: 1.1.1 Algorithm- A finite sequence of steps for accomplishing some computational task. An algorithm must:  Have steps that are simple and definite enough to be done by a computer, and  Terminate after finitely many steps  Notice that an algorithm is a sequence of steps, not a program.  You might use the same algorithm in different programs, or express the same algorithm in different languages, because an algorithm is an entity that is abstracted from implementation details. 1.1.2 Abstract data type (ADT)- : Def 1: A set of values (the carrier set), and operations on those values. Def 2: ADT is defined as a mathematical model with a collection of operations defined on that model. -Abstract Data Type (ADT)-defines the type of data that can be stored in a structure, and the available methods to operate on the data. - Example. In Java, an ADT is modelled as an interface and implemented as a **class****.

  • Classes specify how a given operation on the ADT's data is to be performed.** N.B: A Data Structure is an actual implementation of an ADT i.e. a translation of ADT into statements of a programming language and consists of the following :  The declarations that define a variable to be of that ADT type.  The operations defined on the ADT (using procedures of the programming language).

DATA STRUCTURES AND ALGORITHMS

Properties of ADT  Generalization  Encapsulation (NB: Find out what the above two properties mean)

  • ADT’s are simplification of primitive data types, e.g int, float, char etc.
  • The ADT encapsulates a data type in the sense of the type, such that all operations on that type are localized to one section of the program. i.e. hide implementation details. Advantages of encapsulation include: - Loose coupling between classes - programmer only needs to meet interface specification and not to worry about the details of a given method's functionality. Adaptability -code can be changed without adversely affecting program functionality, due to the presence of a uniform interface. Modularity - the presence of an organized structure that partitions software systems into functional units. EXAMPLES OF ADTS:  Boolean- The carrier set of the Boolean ADT is the set {true, false}.The operations on these values are negation, conjunction, disjunction, conditional, is equal to, and perhaps some others.  Integer- The carrier set of the Integer ADT is the set {.. ., -2, -1, 0, 1, 2,.. }, and the operations on these values are addition, subtraction, multiplication, division, remainder, is equal to, is less than, is greater than, and so on. -Note that although some of these operations yield other Integer values, some yield values from other ADTs (like true and false), but all have at least one Integer value argument.  String- The carrier set of the String ADT is the set of all finite sequences of characters from some alphabet, including the empty sequence (the empty string).Operations on string values include concatenation, length of, substring, index of, and so forth.  Bit String- The carrier set of the Bit String ADT is the set of all finite sequences of bits, including the empty strings of bits, which we denote λ: {λ, 0, 1, 00, 01, 10, 11, 000,.. .}. Operations on bit strings include complement (which reverses all the bits), shifts (which rotates a bit string left or right), conjunction and disjunction (which combine bits at corresponding locations in the strings, and concatenation and truncation.  The thing that makes an abstract data type abstract is that its carrier set and its operations are mathematical entities, like numbers or geometric objects; all details of implementation on a computer are ignored. This makes it easier to reason about them and to understand what they are. For example, we can decide how div and mod should work for negative numbers in the Integer ADT without having to worry about how to make this work on real computers. -Then we can deal with implementation of our decisions as a separate problem.  Once an abstract data type is implemented on a computer, we call it a data type. 1.1.3 Data type- An implementation of an abstract data type on a computer. Thus, for example, the Boolean ADT is implemented as the Boolean type in Java, and the bool type in C++; the Integer ADT is realized

Correctness -- a data structure or algorithm is designed, to work as required for all possible inputs. Example: A sorting algorithm must arrange its inputs in ascending or descending order only.  Efficiency implies fast runtime, and minimal use of computational resources.  Robustness -- a program produces correct outputs for all inputs on any hardware platform on which the program is implemented. N.B Robustness includes the concept of scalability -- the capability of a data structure or algorithm to handle expanding input size without incurring complexity or causing inaccuracy or failure.  Adaptability -- software must be able to be modified or evolved over time to meet environmental changes (e.g., increased CPU speed, client-server implementation, or new functionality to increase market demand). Example: The Year 2000 Problem is an excellent example of poor software design, where date fields in old software were not designed to be large enough to accommodate date codes for an interval greater than 100 years.Reusability -- a given piece of code must be able to be used as a component in different systems or in different application domains without significant modification. Selecting a Data Structure

  1. Analyze the problem to determine the resource constraints.
  2. Determine the basic operations that must be supported.
  3. Select the data structure that best meets these requirements. Guiding questions.
  • Are all data inserted into the data structure at the beginning, or are insertions Interspersed with other operations?
  • Can data be deleted?
  • Are all data processed in some well-defined order, or is random access allowed? 1.1.5 Simple and Structured Data Types  Virtually all programming languages have implementations of several ADTs built into them, thus providing the set of types provided by the language. There are two sorts of built-in types:  Simple types : - The values of the carrier set are atomic, that is, they cannot be divided into parts. Common examples of simple types are integers, Booleans, floating point numbers, enumerations, and characters. Some languages also provide strings as built-in types.  Structured types- : The values of the carrier set are not atomic, consisting instead of several atomic values arranged in some way. Common examples of structured types are arrays, records, classes, and sets. Some languages treat strings as structured types. 2.0 Data (Memory) Allocation 2.1 Memory blocks are allocated for program entities during execution phase and randomly done inside the RAM. - Memory allocation is of two types:

Static memory allocation -Memory is allocated to the entities by the operating system and they remain reserved till the end of the program.  Dynamic memory allocation - Memory is allocated dynamically to the entities of the program. The programmer has the freedom to allocate and free the program entities  Data can be stored on a computer in generally one of three means: contiguous, linked or indexed allocation of memory. Prototypical examples: Contiguous allocation: arrays Linked allocation: linked lists indexed allocation 2.1.1 Contiguous Allocation- The definition of contiguous,( adj ., given by the Oxford English Dictionary) is touching , in actual contact, next in space; meeting at a common boundary, bordering, adjoining; while Meriam-Webster defines it as Touching or connected throughout in an unbroken sequence.

- it is a classical memory allocation model that assigns a process consecutive memory blocks (i.e. memory blocks having consecutive addresses). -When a process needs to execute, memory is requested by the process. The size of the process is compared with the amount of contiguous main memory available to execute the process. If sufficient contiguous memory is found, the process is allocated memory to start execution. Otherwise, it is added to a queue of waiting processes until sufficient free contiguous memory is available.  An array stores n objects in a single contiguous space of memory. Unfortunately, if more memory is required, a request for new memory usually requires copying all information into the new memory. In general, you cannot request for the operating system to allocate to you the next n memory locations.  Figure below shows an array of size four which is first filled. Next, if additional memory is required, a new array (in this case, double the size) is allocated, the information is copied over, and the old array is deallocated. 2.1.2 Linked Allocation- Linked allocation has each item of data stored together with a reference to successor or related data. Usually this reference will be in the form of an address, though other mechanisms exist.

  • Linked data structure –consists of a set of data records (nodes) linked together and organized by references (links or pointers). The link between data is also called a connector. Linked storage such as a linked list associates two pieces of data with each item being stored:  The object(item) itself, and  A reference to the next item

C++ (old) 0 C++ (new) nullptr Symbolically Ø The Node class stores an individual node , but it is still necessary to have a data structure that allows the user to access and manipulate the linked list. At a minimum, such a class must store the address of the first node in the linked list (the head), but it is also useful to store the address of the last node (the tail), as well. A minimal C++ class might be defined as: template class List { private: Node *head; Node *tail; int count; public: // constructor(s)... // accessor(s)... // mutator(s)... }; where we track the number of nodes in the linked list, as well. 2.1.3 Indexed Allocation -With indexed allocation, an array of pointers (possibly NULL) link to a sequence of allocated memory locations as shown in Figure below: Note: one disadvantage of with linked allocation is that it does not support direct accessing since blocks are scattered all over the disk. This is solved by indexed allocation which places all the pointers (references) together into an index block.

-in this scheme, each file is provided with its own index block, which is an array of disk block pointers (addresses). -Matrices tend to use a hybrid of contiguous and indexed allocation e.g. the matrix below:

Can be stored either by storing the rows or the columns, as shown Storing a matrix by row or by column  More ideally, the entries are stored in a contiguous block of memory, and the indices point into this structure, as shown in Figure below: Row-major order and column-major order for storing matrices  C, C++ and python use row-major order while Matlab and FORTRAN use column-major order for storing matrices.

A graph representing an adjacency relation. Suppose we allow arbitrary relations between any two objects in a container

  • Given n objects, there are n^2 – n possible relations
    • If we allow symmetry, this reduces to : 2 2 nn (Consider the above network) 2.2.3 Arrays  Suppose we allow arbitrary relations between any two objects in a container
  • We could represent this using a two-dimensional array - In this case, the matrix is symmetric(refer to the slides for the diagram) 2.2.3.1 Array of Linked Lists Suppose we allow arbitrary relations between any two objects in a container, alternatively, we could use a hybrid: an array of linked lists.

2.2.3.2 Linked Arrays  Other hybrids are linked lists of arrays. It is also possible to link arrays.

  • Something like this is used for the C++ STL deque container For example, the alphabet could be stored either as:
  • An array of 26 entries, or a linked list of arrays of 8 entries. 2.2.4 inodes (hybrid data structure)  The Unix inode structure is used to store the addresses of the blocks of a file. In order to avoid requiring contiguous memory for each file, each file is broken into blocks (usually 4 KiB). The inode uses indexed memory allocation where the first twelve indices store the addresses of the first twelve blocks. Next, the thirteen address points to a block of 1024 addresses for the next 1024 blocks (if the file is bigger than 48 KiB in size).  (Note: this would be on a 32-bit computer where each address is 4 bytes.) The fourteenth address points to a block of 1024 addresses that, in turn, point to blocks of 1024 addresses for files up to 4.05 GiB. The last entry allows for three levels of indirection for files up to approximately 4 TiB.  The Unix inode was used to store information about large files The first twelve entries can reference the first twelve blocks (48 KiB) [Find out what is KiB, GiB,TiB etc].  The next entry is a pointer to an array that stores the next 1024 blocks.

3.0 ELEMENTARY DATA STRUCTURES

RECAP

3.1 Categories of data structures

  • Atomic/Simple Data Types
  • Structured Data types
  • Linear types
  • Non Linear data types  Atomic/Simple Data Types - These are data types that are defined without imposing any structure on their values (have no internal structural relationship) - Examples of atomic types. –Boolean, –Integer –characters  Structured Data types
  • A structured data type has a definition that imposes structure upon its values and has an internal structure that holds between the components.
  • A structure is linear if it has the following 2 properties:  Property P1: Each element is 'followed by' at most one other element.  Property P2: No two elements are 'followed by' the same element. An array is an example of a linearly structured data type. We can write a linearly structured data type like this: A ® B ® C® D (this is one value with 4 parts).
  • Counter example 1 (violates P1):A points to B and C, B¬A ® C
  • Counter example 2 (violates P2): A and B both point to C A ® C ¬ B

Structured data type-Tree Structure

  • Drop the first constraint ( P1 ) and keep the second ( P2 ) we get a tree structure.
  • No two elements are followed by the same element.
  • A is followed by B C D, B by E F, C by G.  Structured Data types: Graph Structure Dropping both P1 and P2 constraints, we get a graph.  Structured Data types: Cyclic Structures:
  • This means that there is sequence of arrows that leads back to where we started.
  • A graph structure that contains a sequence of arrows leading back to the start point is said to be cyclic A linear data structure is one in which, while traversing sequentially, we can reach only one element directly from another. E.g.- Liked List, Array Non Linear data types -structure is one in which, while traversing one can reach more than one element 3.2 Types of Data structures. Data Structure Advantages Disadvantages Array Quick inserts Fast access if index known Slow search Slow deletes Fixed size Ordered Array Faster search than unsorted array Slow inserts Slow deletes Fixed size Stack Last-in, first-out access Slow access to other items Queue First-in, first-out access Slow access to other items Linked List Quick inserts Quick deletes Slow search Binary Tree Quick search Quick inserts Quick deletes (If the tree remains balanced) Deletion algorithm is complex Hash Table Very fast access if key is known Quick inserts Slow deletes Access slow if key is not known Inefficient memory usage Heap Quick inserts Quick deletes Access to largest item Slow access to other items Graph Best models real-world situations Some algorithms are slow and very Complex 3.2.1 Arrays

int scores[100]; // 100 ints, scores[0] to scores[99] char name[40]; // 40 chars, name[0] to name[39] Storage of Array in Main Memory

  • When one declares an array, the compiler sets aside a block of memory large enough to hold the entire array, and individual array elements are stored in sequential memory locations. Use of array Elements
  • Individual elements of the array are accessed using the array name followed by the element subscript enclosed in square brackets. Example 1 Tom [1] = 50, stores the value 50 in the second array element Example 2 Declare an array to contain 5 integer values of type int called Tom. int Tom [5] int Tom [5] = { 16, 2, 77, 40, 12 }; Subscripting
  • Subscripts are used to access an individual element in an array.
  • A subscript is a bracketed expression and the expression in the brackets is known as the index. i.e. name[index] - Example 1 Write a statement that store the value 75 in the third element of in array tom, : Tom[2] = 75;
  • Example A statement that passes the value of the third element of tom to a variable called a, a = tom[2]; N.B. Array uses [ ] bracket to perform two different tasks:
    • One is to specify the size of the arrays when they are declared;
    • The second use is to specify indices for concrete array elements. Example

int billy[5]; // declaration of a new array billy[2] = 75; // access to an element of the array. Store a value to an array element Initializing single dimensional array Int num [5]; Int num [5] = {8, 2, 22, 56, 11} This assigns value 8 to array [0], 2 to array [1], 22 to array [2] etc. 8 2 22 56 11

For example, jimmy represents a multidimensional array of 3 by 5 elements of type int.

- Declared as Example 1. Give a statement that refers to the 9th^ element in array jimmy: A statement that passes the value of the 9th^ element of jimmy to a variable called a, Initializing a multidimensional array A one-dimensional array is usually processed via a ‘for’ loop. Similarly, a two-dimensional array may be processed with a nested for loop: 3.2.1.3 Arrays: Disadvantages  The size of the array is fixed.  Results to wastage of memory space when a large array space is initialized and elements fails to occupy the entire space.  Slow inserts  Slow deletes  Inserting new elements at the front or somewhere at the middle is potentially expensive because existing elements need to be shifted over to make room. int jimmy [3][5]; jimmy[1][3]

3.2.2 Linear Lists

  • Linear list is an ADT in which the positional relations among individual elements are linear (one- dimensional) and elements are of any type.
  • A list is a sequence of zero or more elements of a given type (which we generally call the elementtype )
  • Such a list is usually represented as a comma separated sequence of elements i.e. a0, a1 , a2 ,…, an- where n³0.
  • The number of elements n is said to be the length of the list.
  • Assuming n³1, we say that a0 is the first element and an-1 is the last element. 3 .2.2.1 Operations on linear lists
  • Access the element in position K.
  • Insert new element into list before or after a given k-th element - (Insertion)
  • Delete a specified k-th element ( Deletion)
  • Combine two or more lists into a single list ( Merging/concatenation)
  • Divide the list into two or more lists
  • Sort the List according to the value of a field in elements (Sorting)
  • Search an element in which a certain field has a special value (Searching) Examples of List Operations. L1 = ( dog,cat,rat,bat) InsertA(mouse,Locate(rat,L1),L1) L1 = (dog,cat,mouse rat,bat) Delete(First(L1),L1) L1 = (cat, mouse, rat,bat) L2 = (apple,orange,pear,banana) Concatenate(L1,L2) L1 = (cat, mouse, rat,bat,apple,orange,pear,banana) 3.2.2.2 Lists- Sequential allocation - Lists using Arrays  Suppose we want to store the elements of a list sequentially in a computer.  One method to do this is using a one dimensional array