Docsity

Data Structure (Computer Science), Schemes and Mind Maps of Computer science

Toggle sidebar
bg1
1
Data Structures
Unit-1
Introduction:
WHAT IS DATA STRUCTURE?
In computer science, a data structure is a way of organizing and storing data in a computer
program so that it can be accessed and used efficiently. Data structures provide a means of
managing large amounts of data, enabling efficient searching, sorting, insertion and deletion
of data.
Data structures can be categorized into two types: Primitive data structures and non-
primitive data structures.
Primitive data structures are the most basic data structures available in a programming
language, such as integers, floating-point numbers, characters and Booleans.
Non-primitive data structures are complex data structures that are built using primitive data
types, such as arrays, linked lists, stacks, queues, trees, graphs and hash tables.
The choice of data structure for a particular task depends on the type and amount of data to
be
processed, the operations that need to be performed on the data and the efficiency
requirements of the program. Efficient use of data structures can greatly improve the
performance of a program, making it faster and more memory-efficient. A data structure is a
particular way of organizing data in a computer so that it can be used effectively. The idea is
to reduce the space and time complexities of different tasks.
The choice of a good data structure makes it possible to perform a variety of critical
operations effectively. An efficient data structure also uses minimum memory space and
execution time to process the structure.
Data Structure is a systematic way to organize data in order to use it efficiently.
Following terms are the foundation terms of a data structure.
Interface − Each data structure has an interface. Interface represents the set of
operations that a data structure supports. An interface only provides the list of
supported operations, type of parameters they can accept and return type of these
operations.
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
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download Data Structure (Computer Science) and more Schemes and Mind Maps Computer science in PDF only on Docsity!

Unit- 1 Introduction: WHAT IS DATA STRUCTURE? In computer science, a data structure is a way of organizing and storing data in a computer program so that it can be accessed and used efficiently. Data structures provide a means of managing large amounts of data, enabling efficient searching, sorting, insertion and deletion of data. Data structures can be categorized into two types: Primitive data structures and non- primitive data structures. Primitive data structures are the most basic data structures available in a programming language, such as integers, floating-point numbers, characters and Booleans. Non-primitive data structures are complex data structures that are built using primitive data types, such as arrays, linked lists, stacks, queues, trees, graphs and hash tables. The choice of data structure for a particular task depends on the type and amount of data to be processed, the operations that need to be performed on the data and the efficiency requirements of the program. Efficient use of data structures can greatly improve the performance of a program, making it faster and more memory-efficient. A data structure is a particular way of organizing data in a computer so that it can be used effectively. The idea is to reduce the space and time complexities of different tasks. The choice of a good data structure makes it possible to perform a variety of critical operations effectively. An efficient data structure also uses minimum memory space and execution time to process the structure. Data Structure is a systematic way to organize data in order to use it efficiently. Following terms are the foundation terms of a data structure.Interface − Each data structure has an interface. Interface represents the set of operations that a data structure supports. An interface only provides the list of supported operations, type of parameters they can accept and return type of these operations.

Implementation − Implementation provides the internal representation of a data structure. Implementation also provides the definition of the algorithms used in the operations of the data structure. Characteristics of a Data StructureCorrectness − Data structure implementation should implement its interface correctly.  Time Complexity − Running time or the execution time of operations of data structure must be as small as possible.  Space Complexity − Memory usage of a data structure operation should be as little as possible. Need for Data Structure As applications are getting complex and data rich, there are three common problems that applications face now-a-days.

1. Efficient data processing: Data structures provide a way to organize and store data in a way that allows for efficient retrieval, manipulation and storage of data. For example, using a hash table to store data can provide constant-time access to data. 2. Memory management: Proper use of data structures can help to reduce memory usage and optimize the use of resources. For example, using dynamic arrays can allow for more efficient use of memory than using static arrays. 3. Code reusability: Data structures can be used as building blocks in various algorithms and programs, making it easier to reuse code. 4. Abstraction: Data structures provide a level of abstraction that allows programmers to focus on the logical structure of the data and the operations that can be performed on it, rather than on the details of how the data is stored and manipulated. 5. Algorithm design: Many algorithms rely on specific data structures to operate efficiently. Understanding data structures is crucial for designing and implementing efficient algorithms. 6. Data Search − Consider an inventory of 1 million (106) items of a store. If the application is to search an item, it has to search an item in 1 million (106) items every time slowing down the search. As data grows, search will become slower.

Group Items − Data items that are divided into sub items are called as Group Items.  Elementary Items − Data items that cannot be divided are called as Elementary Items.  Attribute and Entity − An entity is that which contains certain attributes or properties, which may be assigned values.  Entity Set − Entities of similar attributes form an entity set.  Field − Field is a single elementary unit of information representing an attribute of an entity.  Record − Record is a collection of field values of a given entity.  File − File is a collection of records of the entities in a given entity set. Classification of Data Structures Data structures can broadly be classified into two main categories:

1. Primitive Data Structures Primitive data structures are the most basic types of data structures provided by programming languages. They include:  Integer : Whole numbers (e.g., 1, 2, 100).  Float : Numbers with decimal points (e.g., 3.14, 0.001).  Character : Single characters (e.g., ‘A’, ‘B’).  Boolean : Logical values (true or false).

Sample Program in C++ (Primitive Data Types) #include using namespace std; int main() { int num = 10; // Integer float pi = 3.14; // Float char letter = 'A'; // Character bool isHappy = true; // Boolean cout << "Integer: " << num << endl; cout << "Float: " << pi << endl; cout << "Character: " << letter << endl; cout << "Boolean: " << isHappy << endl; return 0; }

2. Non-Primitive Data Structures Non-primitive data structures are more complex and are built using primitive data types. They are further divided into: a. Linear Data Structures In linear data structures, elements are arranged sequentially, and each element has a unique predecessor and successor (except the first and last elements).  Array : A collection of elements of the same type, stored in contiguous memory locations.  Linked List : A collection of nodes where each node contains data and a pointer to the next node.  Stack : A collection of elements following the Last In First Out (LIFO) principle.  Queue : A collection of elements following the First In First Out (FIFO) principle. Sample Program in C++ (Array) #include using namespace std; int main() {

inOrder(root->right); } int main() { Node* root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(5); cout << "In-order Traversal: "; inOrder(root); cout << endl; return 0; } c. File Structures Specialized data structures designed for storing data in secondary storage for efficient retrieval and updates. Examples include B-trees and hash files. Applications of Data Structures: Arrays : Arrays are used to store a collection of homogeneous elements contiguous memory locations. They are commonly used to implement other data structures, such as stacks and queues, and to represent matrices and tables. Linked lists : Linked lists are used to store a collection of heterogeneous elements with dynamic memory allocation. They are commonly used to implement stacks, queues and hash tables. Trees : Trees are used to represent hierarchical data structures, such as file systems, organization charts, and network topologies. Binary search trees are commonly used to implement dictionaries and symbol tables. Graphs : Graphs are used to represent complex relationships between data elements, such as social networks, transportation networks and computer networks. They are commonly used to implement shortest path algorithms and graph traversal algorithms. Hash tables : Hash tables are used to implement associative arrays, which store key-value pairs. They provide fast access to data elements based on their keys.

 Stacks: Stacks are used to store a collection of elements in a last-in-first-out (LIFO) order. They are commonly used to implement undo-redo functionality, recursive function calls and expression evaluation.  Queues: Queues are used to store a collection of elements in a first-in-first-out (FIFO) order. They are commonly used to implement waiting lines, message queues and job scheduling. Common operations on various Data Structures: Data Structure is the way of storing data in computer’s memory so that it can be used easily and efficiently. There are different data-structures used for the storage of data. It can also be defined as a mathematical or logical model of a particular organization of data items. The representation of particular data structure in the main memory of a computer is called as storage structure. For Examples: Array, Stack, Queue, Tree, Graph, etc. Operations on different Data Structure: There are different types of operations that can be performed for the manipulation of data in every data structure. Some operations are explained and illustrated below:  Traversing: Traversing a Data Structure means to visit the element stored in it. It visits data in a systematic manner. This can be done with any type of DS.  Searching: Searching means to find a particular element in the given data-structure. It is considered as successful when the required element is found. Searching is the operation which we can performed on data-structures like array, linked- list, tree, graph, etc.  Insertion: It is the operation which we apply on all the data-structures. Insertion means to add an element in the given data structure. The operation of insertion is successful when the required element is added to the required data-structure. It is unsuccessful in some cases when the size of the data structure is full and when there is no space in the data-structure to add any additional element. The insertion has the same name as an insertion in the data-structure as an array, linked-list, graph, tree. In stack, this operation is called Push. In the queue, this operation is called Enqueue.

Algorithm Specifications: What is an Algorithm? Algorithm Basics The word Algorithm means” A set of finite rules or instructions to be followed in calculations or other problem-solving operations” or” A procedure for solving a mathematical problem in a finite number of steps that frequently involves recursive operations”. Therefore, Algorithm refers to a sequence of finite steps to solve a particular problem. Use of the Algorithms: Algorithms play a crucial role in various fields and have many applications. Some of the key areas where algorithms are used include: Computer Science: Algorithms form the basis of computer programming and are used to solve problems ranging from simple sorting and searching to complex tasks such as artificial intelligence and machine learning. Mathematics: Algorithms are used to solve mathematical problems, such as finding the optimal solution to a system of linear equations or finding the shortest path in a graph. Operations Research : Algorithms are used to optimize and make decisions in fields such as transportation, logistics, and resource allocation. Artificial Intelligence: Algorithms are the foundation of artificial intelligence and machine learning, and are used to develop intelligent systems that can perform tasks such as image recognition, natural language processing and decision-making. Data Science: Algorithms are used to analyze, process, and extract insights from large amounts of data in fields such as marketing, finance and healthcare. These are just a few examples of the many applications of algorithms. The use of algorithms is continually expanding as new technologies and fields emerge, making it a vital component of modern society.

Algorithms can be simple and complex depending on what you want to achieve. It can be understood by taking the example of cooking a new recipe. To cook a new recipe, one reads the instructions and steps and executes them one by one, in the given sequence. The result thus obtained is the new dish is coo ed perfectly. Every time you use your phone, computer, laptop or calculator you are using Algorithms. Similarly, algorithms help to do a task programming to get the expected output. The Algorithm designed is language-independent, i.e. they are just plain instructions that can be implemented in any language, and yet the output will be the same, as expected. What is the need for algorithms? Algorithms are necessary for solving complex problems efficiently and effectively.

1. They help to automate processes and make them more reliable, faster and easier to perform. 2. Algorithms also enable computers to perform tasks that would be difficult or impossible for humans to do manually. 3. They are used in various field such as mathematics, computer science, engineering, finance and 22many others to optimize cases, analyse data, make predictions and provide solutions to problems.

can clearly understand what is to be done. Every fundamental operator in instruction must be defined without any ambiguity.  Finiteness: An algorithm must terminate after a finite number of steps in all test cases. Every instruction which contains a fundamental operator must be terminated within a finite amount of time. Infinite loops or recursive functions without base conditions do not possess finiteness.  Effectiveness: An algorithm must be developed by using very basic, simple, and feasible operations so that one can trace it out by using just paper and pencil. Properties of Algorithm:  It should terminate after a finite time.  It should produce at least one output.  It should take zero or more input.  It should be deterministic means giving the same output for the same input case.  Every step in the algorithm must be effective i.e. every step should do some work. Advantages of Algorithms:  It is easy to understand.  An algorithm is a step-wise representation of a solution to a given problem.  In Algorithm the problem is broken down into smaller pieces or steps hence, it is easier for the programmer to convert it into an actual program. Disadvantages of Algorithms:  Writing an algorithm takes a long time so it is time-consuming.  Understanding complex logic through algorithms can be very difficult.  Branching and Looping statements are difficult to show in Algorithms. How to Design an Algorithm? In order to write an algorithm, the following things are needed as a pre-requisite:

  1. The problem that is to be solved by this algorithm i.e. clear problem definition.
  2. The constraints of the problem must be considered while solving the problem.
  3. The input to be taken to solve the problem.
  4. The output to be expected when the problem is solved.
  5. The solution to this problem, is within the given constraints.

How to express an Algorithm?

  1. Natural Language: Here we express the Algorithm in natural English language. It is too hard to understand the algorithm from it.
  2. Flow Chart: Here we express the Algorithm by making graphical/pictorial representation of it. It is easier to understand than Natural Language. 3. Pseudo Code: Here we express the Algorithm in the form of annotations and informative text written in plain English which is very much similar to the real code but as it has no syntax like any of the programming language, it can’t be compiled or interpreted by the computer. It is the best way to express an algorithm because it can be understood by even a layman with some school level programming knowledge. Recursion: What is Recursion? The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using a recursive algorithm, certain problems can b e s o l v e d q u i t e e a s i l y. Examples o f s u c h p r o b l e m s a r e Towers o f H a n o i (TOH), In order/Preorder/Post order Tree Traversals, DFS of Graph, etc. A recursive function solves a particular problem by calling a copy of itself and solving smaller subproblems of the original problems. Many more recursive calls can be generated as and when required. It is essential to know that we should provide a certain case in order to terminate this recursion process. So, we can say that every time the function calls itself with a simpler version of the original problem. Need of Recursion: Recursion is an amazing technique with the help of which we can reduce the length of our code and make it easier to read and write. It has certain advantages over the iteration technique which will be discussed later. A task that can be defined with its similar subtask, recursion is one of the best solutions for it. For example; The Factorial of a number. Properties of Recursion: Performing the same operations multiple times with different inputs. In every step, we try smaller inputs to make the problem smaller. Base condition is needed to stop the recursion otherwise infinite loop will occur.
  1. Only the "top" disk can be removed.
  2. No large disk can sit over a small disk. Examples: Input: 2 Output: Disk 1 moved from A to B Disk 2 moved from A to C Disk 1 moved from B to C Input: 3 Output: Disk 1 moved from A to C Disk 2 moved from A to B Disk 1 moved from C to B Disk 3 moved from A to C Disk 1 moved from B to A Disk 2 moved from B to C Disk 1 moved from A to C

COMPARISON BETWEEN ITERATIVE AND RECURSIVE FUNCTIONS-

Parameter Recursion Iteration Definition Recursion involves a recursive function which calls itself repeatedly until a base condition is not reached. Iteration involves the usage of loops through which a set of statements are executed repeatedly until the condition is not false. Terminatio n Condition Here termination condition is a base case defined within the recursive function. Termination condition is the condition specified in the definition of the loop. Infinite Case If base case is never reached it leads to infinite recursion leading to memory crash. If condition is never false, it leads to infinite iteration with computers CPU cycle being used repeatedly. Memory Usage Recursion uses stack area to store the current state of the function, due to which memory usage is high. Iteration uses the permanent storage area only for the variables involved in its code block, hence memory usage is less. Code Size Code size is comparatively smaller. Code size is comparatively larger. Performan ce Since stack are is used to store and restore the state of recursive function after every function call, performance is comparatively slow. Since iteration does not have to keep re- initializing its component variables and neither has to store function states, the performance is fast. Memory Runout There is a possibility of running out of memory, since for each function call stack area gets used. There is no possibility of running out of memory as stack area is not used. Overhead Recursive functions involve extensive overhead, as for each There is no overhead in Iteration.

OPERATION ON ARRAYS

There are a number of operations that can be performed on an array which are:

  1. Traversal
  2. Sorting
  3. Insertion
  4. Deletion
  5. Searching
  6. Merging Traversal: Traversal means accessing each array element for a specific purpose, either to perform an operation on them. Sorting: It is a process of arranging the elements in the array. Insertion: it is a process of adding a new element to the array in the specified location. Deletion: it is a process of removing an element from the array from the specified location. Searching: it is a process of finding an element in an array Merging: it is a process of combining the elements of two array. ABSTRACT DATA TYPE(ADT): Abstract Data Type (ADT) is a data type, where only behaviour is defined but not implementation. Examples: Array, List, Queue, Stack, Tree are ADTs.

MEMORY REPRESENTATION

One dimensional array- Let’s first declare and initialise an one-dimensional array num with 10 elements int num[] = {-3, 5, 12, 89, 91, 94, 23, 34, 45, 76}; Memory Representation of an array with elements, address and indexes Like other variables and constants an array also requires memory blocks to store the elements. An array is a collection of similar elements, so it requires contiguous memory blocks. Look at the image depicted above , at the bottom of the image the addresses of each elements are displayed. Now let’s understand the addressing and indexing of the num array. Addressing- The type of num is int , so each elements of the num array will take 2 bytes of memory. For example, consider the starting address of first memory block is 2000. So the next elements of the array will get next contiguous 4 bytes memory block and the memory address will be 2002 (as 2000 + 2 bytes) and so on for other elements. In the above figure, the addresses are displayed here, are the starting address of each memory block assigned to individual element of the array. 2 bytes memory block assigned to each element What is Indexing Indexing is a process to get the location of an element in the array. So, when we write num[0] , it informs the compiler about the location of the first element. In C, array indexing is started from 0 for the first element. So, 0 will be passed with subsscripting operator [ ] , to access the first element of the array.