Docsity

Introduction to Data Structures and Algorithms, Study notes of Computer science

Toggle sidebar
bg1
Unit-I DATA STRUCTURES
1
Unit – I
Introduction to Data Structures
1.1. Data Structures:
A data structure is a particular way of organising data in a computer so that it can be used
effectively. The idea is to reduce the space and time complexities of different tasks.
Need of Data Structure:
The structure of the data and the synthesis of the algorithm are relative to each other. Data
presentation must be easy to understand so the developer, as well as the user, can make an
efficient implementation of the operation.
• Data structures provide an easy way of organising, retrieving, managing, and storing
data.
• Data structure modification is easy.
• It requires less time.
• Save storage memory space.
• Data representation is easy.
• Easy access to the large database
1.1.1. Classification of Data Structures:
The classification of data structures can be explored into two main types:
Primitive and Non-Primitive.
1. Primitive Data Structure
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Partial preview of the text

Download Introduction to Data Structures and Algorithms and more Study notes Computer science in PDF only on Docsity!

Unit – I

Introduction to Data Structures

1.1. Data Structures: A data structure is a particular way of organising data in a computer so that it can be used effectively. The idea is to reduce the space and time complexities of different tasks. Need of Data Structure : The structure of the data and the synthesis of the algorithm are relative to each other. Data presentation must be easy to understand so the developer, as well as the user, can make an efficient implementation of the operation.

  • Data structures provide an easy way of organising, retrieving, managing, and storing data.
  • Data structure modification is easy.
  • It requires less time.
  • Save storage memory space.
  • Data representation is easy.
  • Easy access to the large database 1.1.1. Classification of Data Structures: The classification of data structures can be explored into two main types: Primitive and Non-Primitive. 1. Primitive Data Structure

The primitive data structures are also known as built-in data structures as they are basic data structures in many high-level programming languages. They operate directly according to the machine’s instructions. The following are the various types of data structures that are primitive.

  1. Boolean: The data in this type is either true or false or positive or negative. Boolean type depicts whether the data is positive or negative. Here binary variables, logical values, and algebra are used.
  2. Integer: In this data structure type, both positive and negative numbers along with zero are stored. These integers help with the arithmetic operations.
  3. Floating-point Numbers: In this type of DS, approximate values are used in the form of a formula to allow the trade-off between range and precision. They include real numbers positive, negative, fractions, and numbers with decimal points.
  4. Character: It stores information in a fixed-length field or variable-length string. The fixed-length field is used by the CHAR data type. Numbers, alphabets, and special characters are all included but represented inside single or double inverted commas.
  5. Pointer: The pointer data structure stores the memory address of another variable as its value. 2. Non-Primitive Data Structure Non-primitive data structures are complex data structures that use primitive data structures to form a structure of their own. This is why they are also known as derived types. Though in- built support is provided for these data structures by many programming languages, they are mostly user-defined. Non-primitive data structures can be classified into linear and non- linear data structures. Operations in data structures : Common data structure operations with examples:
  6. Insertion: Adding an element to the data structure. For example, inserting an element into an array or a linked list.
  7. Deletion: Removing an element from the data structure. For example, removing an element from a array or a linked list.
  8. Search: Finding an element in the data structure. For example, searching for a specific key or value in array or a linked list.
  9. Traversal: Visiting every element in the data structure. For example, printing all elements of an array or a linked list.

▪ Stack uses two operations for implementing the LIFO principle, push and pop. ▪ The push () method inserts the element in the stack and the pop() method retrieves one or more elements from the stack. ▪ Stacks are used to maintain the call logs in mobile phones, to keep track of visited pages on a browser, etc. Queue: The queue data structure: ▪ Uses the FIFO or First In First Out principle. ▪ Here the element stored first or the oldest element in the structure is retrieved first. It is retrieved by the dequeue () method. ▪ It is used for handling website traffic, asynchronous transfer of data, switching to multiple applications on an operating system, etc. 1.1.3. Non-linear Data Structure In the non-linear data structure, the elements are stored in a non-linear or non-sequential manner. It is complicated since values are arranged at multiple levels, that is, each value is connected to one or more values. The following are the types of non-linear data structures. Graph: ▪ The graph is a node-based type of DS that has a list of other nodes that are linked in the graph. ▪ It has two components, vertices, and edges. ▪ The edges are used to connect vertices. ▪ This data structure is used for network representation. ▪ The graph data structure is used to represent the flow of computation, in Google Maps, to study molecules of physics and chemistry, etc. Tree: ▪ A subtype of the graph that represents its elements in a hierarchical order. ▪ A tree uses a node-like structure to make a hierarchical form and each node here represents a value. ▪ The root node is the uppermost node of the tree and the leaf node is the node at the bottom of the tree.

▪ This data structure imposes a rule that nodes of a tree do not create loops in the data structure. ▪ A tree is used for indexing databases, scanning, parsing, and generating code in compiler design, in routers in computer networks, social networking sites, etc. 1.1.4. Abstract Data Types An Abstract Data Type (ADT) is a conceptual model that defines a set of operations and behaviours for a data structure, without specifying how these operations are implemented or how data is organized in memory. The definition of ADT only mentions what operations are to be performed but not how these operations will be implemented. It does not specify how data will be organized in memory and what algorithms will be used for implementing the operations. It is called “abstract” because it provides an implementation-independent view. The process of providing only the essentials and hiding the details is known as abstraction. Features of ADT Abstract data types (ADTs) are a way of encapsulating data and operations on that data into a single unit. Some of the key features of ADTs include:

  • Abstraction: The user does not need to know the implementation of the data structure only essentials are provided.
  • Better Conceptualization: ADT gives us a better conceptualization of the real world.
  • Robust: The program is robust and has the ability to catch errors.
  • Encapsulation : ADTs hide the internal details of the data and provide a public interface for users to interact with the data. This allows for easier maintenance and modification of the data structure. 1.1.5. Time Complexity: Time complexity measures how long an algorithm takes to complete as a function of the input size. It essentially quantifies the growth of execution time with increasing input. Notation: Time complexity is commonly expressed using Big O notation, which provides an upper bound on the algorithm's runtime. O (1) (Constant Time): The algorithm's runtime is the same regardless of the input size (e.g., accessing an element in an array by its index).

3. Theta Notation (Θ) - Theta Notation is used to describe the exact bound of an algorithm's running time. It tells us the average-case scenario, where the running time is bound both above and below by the same function. - Theta notation focuses on the typical running time of an algorithm. It shows that the algorithm's running time is both at least and at most a certain function of the input size. 1.2 sequential storage representation Sequential storage representation, also known as array or indexed storage, is a method of storing data elements in memory such that they occupy contiguous memory locations. This means the elements are stored one after the other, with each element's address determined by a fixed distance from the previous element, as demonstrated in arrays. 1.2.1. Various sorting techniques ➢ internal Sorting in data structure Internal sorting in data structure is used when the entire dataset can fit within main memory (RAM), allowing for faster processing without requiring external storage access.

  • Characteristics: o Memory-Based Processing: Works entirely in RAM, which is faster than accessing external storage. o Best for Small to Medium Datasets: Suitable when data size does not exceed available memory.
  • Common Algorithms: o Quick Sort, Merge Sort, Heap Sort o Typical Use: Internal sorting is used in applications where data fits in memory, such as sorting lists or arrays in moderate-sized datasets. ➢ External Sorting in data structure External sorting in data structure is required when the dataset is too large to fit into main memory and must use external storage for sorting operations.
  • Characteristics: o Disk-Based Processing: Requires data to be read from and written to external storage, impacting performance.

o Best for Large Datasets: Necessary when data exceeds memory capacity, such as in large-scale data processing. Common Algorithms : o External Merge Sort, Multi-way Merge Sort. Typical Use: Used in systems managing large data files, such as database systems, where sorting needs exceed available RAM. 1.2.1.1. define sorting Sorting in data structures is the process of rearranging elements in a specific order, such as numerical, alphabetical, or chronological, to make searching, retrieving, and manipulating data more efficient. 1.2.1.2. Need of sorting

  • Efficient Searching – Enables faster search (e.g., binary search).
  • Organized Data – Easier to read and interpret.
  • Optimized Algorithms – Many algorithms work better or require sorted data.
  • Faster Data Processing – Speeds up operations like finding duplicates or extremes.
  • Improves Decision Making – Quick analysis of top/bottom values.
  • Database Efficiency – Used in indexing structures like B-Trees. 1.2.1.3. List the methods of sorting ➢ Bubble Sort ➢ Selection Sort ➢ Insertion Sort ➢ Merge Sort ➢ Quick Sort 1.2.1.4. Explain the following

➢ Bubble sort:

Bubble Sort is a simple way to sort a list of items, like numbers or letters, in order. The basic idea is to repeatedly step through the list, compare each pair of adjacent items, and swap them if they are in the wrong order. This process is repeated until no more swaps are needed, meaning the list is sorted. Bubble Sort Algorithm Step 1: Start at the beginning of the list. Step 2: Compare each pair of adjacent elements.

int main() { int n,i,arr[20]; printf("Enter the number of elements: "); scanf("%d", &n); printf("Enter %d elements:\n", n); for (i = 0; i < n; i++) { scanf("%d", &arr[i]); } printf("Original array: "); printArray(arr, n); bubbleSort(arr, n); printf("Sorted array: "); printArray(arr, n); getch(); return 0; } Output: Enter the number of elements: 5 Enter 5 elements: 5 3 8 4 2 Original array: 5 3 8 4 2 Sorted array: 2 3 4 5 8 Complexity analysis of bubble sort: Case Time Complexity Explanation Space Complexity Best Case O(n) Single pass, no swaps detected O(n) Average Case O(n 2 ) Multiple passes with swaps O(n)

Worst Case O(n 2 ) Every pair compared and swapped O(n) Time Complexity is O (n 2 ) Space Complexity is O(n)


➢ Selection sort: Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted. Working of selection sort:

  1. Initial Assumption: Assume the first element is the smallest.
  2. Comparison: Compare this element with all other elements in the unsorted part of the array to find the actual smallest element.
  3. Swapping: Swap the smallest element found with the first element of the unsorted part.
  4. Repeat: Move to the next element and repeat the process for the remaining unsorted part of the array. Selection sort algorithm: Step 1 − Set MIN to location 0 Step 2 − Search the minimum element in the list Step 3 − Swap with value at location MIN Step 4 − Increment MIN to point to next element Step 5 − Repeat until list is sorted Implementation of selection sort: Source code: #include <stdio.h> void selectionSort(int arr[], int n) { int i, j, minIndex, temp; for (i = 0; i < n - 1; i++) { minIndex = i; for (j = i + 1; j < n; j++) {

printArray(arr, n); selectionSort(arr, n); printf("Sorted array: "); printArray(arr, n); getch(); return 0; } Output: Enter the number of elements: 5 Enter 5 elements: 29 10 14 37 13 Original array: 29 10 14 37 13 Sorted array: 10 13 14 29 37 Complexity Analysis of Selection Sort Time Complexity Selection Sort always makes the same number of comparisons, regardless of input order.

  • Best Case: O(n^2 )
  • Average Case: O(n^2 )
  • Worst Case: O(n^2 ) Because it always performs n (n−1)/2 comparisons.
  • Outer loop runs n−1times
  • Inner loop runs decreasingly from n−1to 1 Total comparisons=n (n−1)/ Space Complexity
  • In-place algorithm: only uses a few variables
  • Space Complexity: O(1)