0% found this document useful (0 votes)
10 views16 pages

DS Unit 1

Ok for this

Uploaded by

kanusha4304
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views16 pages

DS Unit 1

Ok for this

Uploaded by

kanusha4304
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

I B.

Tech II SEM R23 BIET

UNIT-I
Introduction to Linear Data Structures:
1. Definition and importance of linear data structures,
2. Abstract data types (ADTs) and their implementation,
3. Overview of time and space complexity
4. Analysis for linear data structures.
5. Searching Techniques: Linear & Binary Search,
6. Sorting Techniques: Bubble sort, Selection sort, Insertion Sort

1. Definition and importance of linear data structures,


Data structure where the data elements are organized sequentially or linearly where
the elements are attached to its preceding and subsequent adjacent element is called
a linear data structure. In the linear data structure, single level is involved.
Therefore, we can traverse all the elements in single run only. Linear data structures
are easy to implement as computer memory is organized linearly.

Examples include arrays, stack, queue, linked list, etc.

Linear data structures are two subcategories based on memory allocation changes:

Static data structures have a fixed size. Elements can change order, but the
memory allocation for the data structure stays the same. An example static data
structure is an array.
Dynamic data structures have a modular size. Runtime changes allow altering the
data structure size. Examples of dynamic data structures include queues, stacks, and
lists.

Importance:
Linear data structures include arrays, linked lists, stacks, and queues. They are
crucial in many computing tasks due to their simplicity and efficiency in accessing
and manipulating data.

Arrays: Elements are stored in contiguous memory locations, allowing for


constant-time access to any element with its index.
Linked Lists: Elements are linked together via pointers, providing flexibility in
insertion and deletion operations.
Stacks: Follows the Last In, First Out (LIFO) principle, making them suitable for
tasks such as function call management and expression evaluation.
I B.Tech II SEM R23 BIET

Queues: Follows the First In, First Out (FIFO) principle, making them suitable for
tasks such as process scheduling and buffering.

Characteristics of Linear Data Structure


 It's a data structure that stores and manages data in a linear order.
 The data elements of the sequence are linked from one to the next.
 Implementing the linear structure of data within a computer's RAM is
simple, provided that the data are organized sequentially.
 Array, queue. Stack, linked list, etc., are a few examples of such a structure.
 Only one relationship exists between the data elements in the data structure.
 Because the data elements are stored on a single level, it is possible to
traverse the data elements in one run.
 If a linear data storage structure is used, it is not well utilized.

2. Abstract data types (ADTs) and their implementation,


Definition: An abstract data type (ADT) is a data type that is organized in such a way that
the specification of the objects and the specification of the operations on the objects is
separated from the representation of the objects and the implementation of the operations.

Implementation:
A sparse matrix is a matrix that contains mostly zero values. Instead of storing all elements
in the matrix, this ADT focuses only on non-zero elements, saving memory space.

Functions:
 Create(max_row, max_col): Creates a sparse matrix with the given maximum row
and column sizes. It initializes the matrix to hold up to max_row x max_col items.
 Transpose(a): Produces a new matrix by interchanging the row and column values
of every triple in matrix a.
 Add(a, b): Adds two sparse matrices a and b together if they have the same
dimensions. It returns the matrix produced by adding corresponding items (with
identical row and column values).
 Multiply(a, b): Multiplies two sparse matrices a and b if the number of columns in a
equals the number of rows in b. It returns the matrix d produced by multiplying a by
b according to a specified formula.
Operations:
 Each triple <row, column, value> represents a non-zero element in the sparse
matrix.
 Max-row and max-col represent the maximum row and column sizes respectively.
 The index function retrieves the value of a specific element at row i and column j.
 The item set represents the set of possible values that can be stored in the matrix.

Example:
Consider two sparse matrices, A and B, defined as follows:
I B.Tech II SEM R23 BIET

Matrix A:
1 0 3
0 2 0
0 0 0

Matrix B:
0 0 1
0 4 0
2 0 0

Operations:

Create(max_row, max_col):

Let's create matrices A and B with a maximum size of 3x3.

Transpose(a):

Transpose matrix A:
1 0 0
0 2 0
3 0 0

Transpose matrix B:

0 0 2
0 4 0
1 0 0

Add(a, b):

Matrix A + Matrix B:

A[1,1] + B[1,1] = 1 + 0 = 1
A[1,3] + B[1,3] = 3 + 1 = 4
A[2,2] + B[2,2] = 2 + 4 = 6
A[3,1] + B[3,1] = 0 + 2 = 2

1 0 4
0 6 0
2 0 0

Multiply(a, b):

Matrix A * Matrix B:
I B.Tech II SEM R23 BIET

2 0 1
0 8 0
0 0 0

Implementation in C:

// Define functions for Create, Transpose, Add, Multiply, etc.


// Use structures and arrays to represent sparse matrices and triples.
// Perform mathematical operations based on the defined functions and structures.

#include <stdio.h>
#include <stdlib.h>

// Define a structure for a triple <row, column, value>


struct Triple {
int row;
int col;
int value;
};
// Define a structure for a Sparse-Matrix
struct SparseMatrix {
struct Triple *triples; // Array of triples
int max_row;
int max_col;
int num_triples; // Number of non-zero elements
};
// Function to create a Sparse-Matrix
struct SparseMatrix* create_sparse_matrix(int max_row, int max_col) {
struct SparseMatrix *matrix = (struct SparseMatrix*)malloc(sizeof(struct SparseMatrix));
// Initialize other attributes such as max_row, max_col, num_triples
matrix->max_row = max_row;
matrix->max_col = max_col;
matrix->num_triples = 0;
matrix->triples = NULL;
return matrix;
}
// Function to add a triple to the Sparse-Matrix
void add_triple(struct SparseMatrix *matrix, int row, int col, int value) {
// Check if the triple already exists at the given position
// If it does, update its value; otherwise, add a new triple
// Increase the num_triples count
// Reallocate memory if necessary
}
// Function to transpose the Sparse-Matrix
struct SparseMatrix* transpose(struct SparseMatrix *matrix) {
// Create a new Sparse-Matrix with transposed dimensions
I B.Tech II SEM R23 BIET

// Iterate through each triple in the original matrix


// Swap row and column values and add to the transposed matrix
// Return the transposed matrix
}
// Function to add two Sparse-Matrices
struct SparseMatrix* add_matrices(struct SparseMatrix *matrix_a, struct SparseMatrix
*matrix_b) {
// Check if the matrices have the same dimensions
// Create a new Sparse-Matrix to store the result
// Iterate through each triple in both matrices
// Add corresponding values and add to the result matrix
// Return the result matrix
}
// Function to multiply two Sparse-Matrices
struct SparseMatrix* multiply_matrices(struct SparseMatrix *matrix_a, struct SparseMatrix
*matrix_b) {
// Check if the matrices can be multiplied (dimensions)
// Create a new Sparse-Matrix to store the result
// Perform matrix multiplication according to the specified formula
// Return the result matrix
}

// Function to print the Sparse-Matrix


void print_matrix(struct SparseMatrix *matrix) {
// Iterate through each triple and print row, column, and value
}

// Function to free memory allocated for Sparse-Matrix


void free_matrix(struct SparseMatrix *matrix) {
// Free memory allocated for triples array
// Free memory allocated for the Sparse-Matrix structure
}

// Define other helper functions as needed

int main() {
// Use the defined functions to create, manipulate, and print sparse matrices
return 0;
}
I B.Tech II SEM R23 BIET

3. Overview of time and space complexity


Space Complexity:

Space complexity refers to the total amount of memory (primary memory) a program needs
to run to its completion. It can be broken down into three main components:

1. Instruction Space: This component depends on factors such as the compiler


generating machine or binary code and the target computer.
2. Data Space: It heavily depends on the computer's architecture, compiler, and the
magnitude of data that the program operates on. Different data types require
different amounts of memory to store.
3. Stack Space: Each time a function is called, data such as the return address, local
variables, formal parameters, and bindings of references are recorded in the stack.

Efficient use of space can be achieved by:


 Selecting the smallest data type required.
 Understanding compiler behavior and compilation settings.
 Choosing non-recursive algorithms where applicable.

Space (S) requirements for any algorithm can be expressed as:

S(p) = C + Sp

Where:
- C is the fixed part, including instruction space and space for single and fixed-size
variables.
- Sp is the variable part, representing space needed for referenced variables, dependent
on instance characteristics and recursion state space.

Time Complexity:

Time complexity measures the amount of time it takes for an algorithm to run. Absolute
time complexity is determined by the number of instructions executed multiplied by the
time taken to execute one instruction.

In general, algorithm time complexity is categorized as:

 Worst Case: The maximum time required for the program to execute. It is represented
by the Big O notation (\( O \)).
 Average Case: The average time required for program execution. Represented by the
Theta notation (\( \Theta \)).
 Best Case: The minimum time required for program execution. Represented by the
Omega notation (\( \Omega \)).

Examples of Corrected Content:


I B.Tech II SEM R23 BIET

1. Space Complexity Example:


 Fixed part C: Instruction space, space for fixed-size variables.
 Variable part Sp: Space needed for dynamic data structures like arrays or linked
lists.

2. Time Complexity Example:


- For a sorting algorithm:
- Worst case: O(n2) (e.g., Bubble Sort).
- Average case: O(n log n) (e.g., Merge Sort).
- Best case: O(n) (e.g., Insertion Sort).

4. Analysis for linear data structures.


Arrays:
Space Complexity: Arrays have a space complexity of O(n), where n is the number of
elements in the array. This is because arrays allocate contiguous memory blocks to store
elements.

Time Complexity:
Access: O(1) - accessing elements by index.
Search: O(n) - linear search if the elements are unsorted.
Insertion/Deletion:
At the beginning: O(n) - requires shifting elements.
At the end: O(1) - if appending to the end.
In the middle: O(n) - requires shifting elements.

Linked Lists:
Space Complexity: Linked lists have a space complexity of O(n), where n is the number of
elements in the list. This is because each element requires additional memory for the
pointer to the next element.

Time Complexity:
Access: O(n) - sequential traversal required.
Search: O(n) - linear search if the elements are unsorted.
Insertion/Deletion:
At the beginning: O(1) - no shifting required.
At the end: O(n) - traversal required to reach the end.
In the middle: O(n) - traversal required to find insertion point.

Stacks:
Space Complexity: Stacks have a space complexity of O(n), where n is the maximum
number of elements in the stack.

Time Complexity:
Access/Search: O(n) - no direct access to arbitrary elements.
I B.Tech II SEM R23 BIET

Push/Pop: O(1) - constant time complexity for adding/removing elements from the top of
the stack.

Queues:
Space Complexity: Queues also have a space complexity of O(n), where n is the maximum
number of elements in the queue.

Time Complexity:
Access/Search: O(n) - no direct access to arbitrary elements.
Enqueue/Dequeue: O(1) - constant time complexity for adding/removing elements from the
front/rear of the queue.

5. Searching Techniques: Linear & Binary Search


Define Searching?
The process of finding the desired information from the set of items stored in the form of
elements in the computer memory is referred to as ‘searching in data structure’. These sets
of items are in various forms, such as an array, tree, graph, or linked list. Another way of
defining searching in the data structure is by locating the desired element of specific
characteristics in a collection of items.

Searching refers to the operation of fnding the position of a given item in a collection of
items. Searching in data structure refers to the process of fnding the location of an element
in a list.

State the need of Searching?


To check for an element or retrieve an element from any data structure where the data is
stored. Based on the type of search operation,

Two types of searching:


a. Internal search
The searching method in which all elements remain sustained in main memory is called
internal search. The time required is less but is perfect for a small amount of data.
Linear search, binary search, binary search tree and AVL tree are internal searching
techniques.

b. External search:
The searching method in which elements are kept in secondary storage is called external
search. The time required is longer, and the perfect search technique for a lot of data.
B tree and B+ tree are external searching techniques.

Sequential Search or Linear Search


In linear search, we access each element of an array one by one sequentially and see
whether or not it is desired element. A search will be unsuccessful if all the elements are
accessed, and the desired element is not found.
I B.Tech II SEM R23 BIET

Algorithm of Linear Search


1. Start.
2. Traverse the array using any other loop.
3. In every iteration, compare the key element value with the current value of the
array.
i. If the value gets a match, then print the current position or location of the array
element.
ii. If the value does not match, move on to the next array element by incrementing
the array index by one.
iii. If the last element in the array is checked with key elements and no match is
found, then print the key element that is not present in your array or list.
4. Stop.

Program of Linear Search


#include<stdio.h>
int main() {
int a[50], n, i, item, loc=-1;
printf("\n Enter size of array or list: ");
scanf("%d",&n);
printf(" Enter values in the array: \n");
for(i=0;i<n;i++) {
scanf("%d",&a[i]);
}
printf("\n Enter the number which you want to search: ");
scanf("%d",&item);
for(i=0;i<n;i++) {
if(item==a[i]) {
loc=i;
break;
}
}
if(loc>=0) {
printf("\n %d is found at the array index %d and at position %d",item,loc,loc+1);
} else {
printf("\n Item does not exist in the list");
}
return 0;
}

Advantages of Linear Search


i. It is a very simple method.
ii. It does not require the data to be ordered form.
iii. It does not require any additional data structure.

Disadvantages of Linear Search


I B.Tech II SEM R23 BIET

i. If several elements are very large, this method of searching is very insufficient and
slow.

Binary Search Basics


Binary search is a very efficient search technique, which works for sorted lists only either
in ascending or in descending order. Binary search is a fast searching algorithm with the
worst-case time complexity of Ο (log2 n). This search algorithm is based on the divide-
and-conquer principle. For this algorithm to work properly, the data collection or list must
be in sorted order.

Binary Search Algorithm

1. Start.
2. The array must be in ascending or descending sorted order.
Then find the middle element of the array, which will be referred to as mid.
3. Compare the middle element, mid with searched element or key element, key.
4. There are three cases assumed that the array is in ascending order:
i. If mid = key, that is, if mid is the desired element, then the search is successful.
ii. If mid > key, that is, the mid element is greater than key element, then search only
in the first half of the array.
iii. If mid < key, that is, the mid element is less than key element, then search only in
the second half of the array, considered array elements are sorted in ascending
order.
5. Repeat the above steps 1–3 until the key element is found.
6. Stop.

Program of Binary Search


#include<stdio.h>
int main() {
int a[50] , i , n , loc , mid , beg , end , item , flag=0;
printf("\n Enter the size of array or list:");
scanf("%d",&n);
printf("Enter the elements in array:\n");
for(i=0;i<n;i++) {
scanf("%d",&a[i]);
}printf("Enter the element which you want to search:");
scanf("%d",&item);
loc=0;
beg=0;
end=n-1;
while((beg<=end)&&(item!=a[mid])){
mid=(beg+end)/2;
if(item==a[mid]) {
printf("\n Searched element is found");
loc=mid;
printf("\n Location of the element is %d and array index is %d",loc+1,loc);
I B.Tech II SEM R23 BIET

flag=1;
} if(item<a[mid]) end=mid-1;
else
beg=mid+1;
} if(flag==0)
printf("\n Item is not found in the list.");
return 0;
}

Advantages of Binary Search


 Worst-case time complexity of the binary search is very effcient.
 Compared to linear search, the binary search algorithm is much faster.
 A binary search is a simple algorithm for fnding an element in a sorted list.

Disadvantages of Binary Search


 Does not apply to unsorted records. Data has to be in sorted order always before
applying binary search.
 Binary search is a more complicated algorithm than linear search.
 Binary search doesn't work well for small lists.
 Binary search is convenient for array-like direct access structures, but not
appropriate for a linked list-like storage structures.

6. Sorting Techniques: Bubble sort, Selection sort, Insertion Sort


What is Sorting?
Sorting is a process of ordering or placing a list of elements from a collection in some kind of
order. It is nothing but storage of data in sorted order. Sorting can be done in ascending and
descending order. It arranges the data in a sequence which makes searching easier.

What is the need of sorting?


Sorting can often reduce the complexity of a problem; it is an important algorithm in Computer
Science. These algorithms have direct applications in searching algorithms, database
algorithms, divide and conquer methods, data structure algorithms,

Bubble Sort:
Bubble Sort Algorithm:
1. Start traversing the array from the first element to the second last element.
2. Compare each pair of adjacent elements.
3. If the elements are in the wrong order (i.e., the current element is greater than
the next element), swap them.
4. Continue this process until the end of the array.
5. After the first pass, the largest element will be at the end of the array.
6. Repeat steps 1-5 for the remaining unsorted elements (excluding the already
sorted elements at the end of the array).
7. Continue this process until the entire array is sorted.
I B.Tech II SEM R23 BIET

#include <stdio.h>

// Function to perform Bubble Sort


void bubbleSort(int arr[], int n) {
int i, j;
for (i = 0; i < n-1; i++) {
// Last i elements are already in place, so we don't need to check them again
for (j = 0; j < n-i-1; j++) {
// Swap if the element found is greater than the next element
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main() {
int n;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n]; // Declare an array of size n
// Read array elements from the user
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("\nOriginal array: \n");
for (int i=0; i < n; i++) {
printf("%d ", arr[i]);
}
// Call Bubble Sort function
bubbleSort(arr, n);
printf("\n\nSorted array: \n");
for (int i=0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
//output
Enter the number of elements in the array: 5
Enter 5 elements:
4
2
7
I B.Tech II SEM R23 BIET

1
5

Original array:
42715

Sorted array:
12457

Selection Sort:
Selection Sort Algorithm:
1. Start with the first element of the array as the minimum (assuming it's the
smallest).
2. Traverse the array from the second element to the last element.
3. Find the minimum element in the unsorted part of the array.
4. Swap the minimum element with the first element of the unsorted part.
5. Repeat steps 2-4 until the entire array is sorted.

#include <stdio.h>
// Function to perform Selection Sort
void selectionSort(int arr[], int n) {
int i, j, min_idx;
for (i = 0; i < n-1; i++) {
min_idx = i;
// Find the minimum element in the unsorted part of the array
for (j = i+1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
// Swap the minimum element with the first element of the unsorted part
int temp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}
}
int main() {
int n;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
I B.Tech II SEM R23 BIET

int arr[n]; // Declare an array of size n


// Read array elements from the user
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("\nOriginal array: \n");
for (int i=0; i < n; i++) {
printf("%d ", arr[i]);
}
// Call Selection Sort function
selectionSort(arr, n);
printf("\n\nSorted array: \n");
for (int i=0; i < n; i++) {
printf("%d ", arr[i]);
}

return 0;
}
Enter the number of elements in the array: 5
Enter 5 elements:
9
5
2
7
1

Original array:
95271

Sorted array:
12579

Insertion Sort:
Insertion Sort Algorithm:

1. Start with the second element of the array.


2. Assume the first element to be sorted.
3. Consider the next element and insert it into the correct position among the sorted elements
to its left.
4. Repeat step 3 for all remaining elements in the array.
I B.Tech II SEM R23 BIET

#include <stdio.h>

// Function to perform Insertion Sort


void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;

// Move elements of arr[0..i-1], that are greater than key, to one position ahead of their
current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

int main() {
int n;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);

int arr[n]; // Declare an array of size n

// Read array elements from the user


printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

printf("\nOriginal array: \n");


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

// Call Insertion Sort function


insertionSort(arr, n);

printf("\n\nSorted array: \n");


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
I B.Tech II SEM R23 BIET

return 0;
}

Enter the number of elements in the array: 6


Enter 6 elements:
9
5
2
7
1
4

Original array:
952714

Sorted array:
124579

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy