0% found this document useful (0 votes)
14 views19 pages

Algorithms& Data Structures Notes

The document outlines a course on Algorithms and Data Structures, detailing objectives, course outcomes, and a structured curriculum covering topics like data organization, linked lists, stacks, recursion, and queues. It includes essential readings, references, e-resources, and journals for further study. Additionally, it provides sample C programs for array manipulation and string operations, illustrating practical applications of the concepts taught.

Uploaded by

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

Algorithms& Data Structures Notes

The document outlines a course on Algorithms and Data Structures, detailing objectives, course outcomes, and a structured curriculum covering topics like data organization, linked lists, stacks, recursion, and queues. It includes essential readings, references, e-resources, and journals for further study. Additionally, it provides sample C programs for array manipulation and string operations, illustrating practical applications of the concepts taught.

Uploaded by

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

ALGORITHMS & DATA STRUCTURES

PAPER CODE: CBCA 301


CREDITS: 3
PERIODS/WEEK: 3
MAX. MARKS: 100.00
OBJECTIVE: The course will enable the students to
1. Learn the concepts of data organization in effective manner.
2. Understand Data Structures, Arrays, Strings, Pointers, Structures & Unions, Algorithms & their
implementation.
Course Outcomes (COs):

Course Outcome (at course Learning and teaching strategies Assessment Strategies
level)

The students will: Interactive Lectures, Discussion, Class test, Semester end
Tutorials, Reading assignments, examinations, Quiz, Solving
Demonstrations. problems in tutorials,
CO98. Analyze algorithm and its Assignments, Presentation,
complexity while examining Individual and group projects.
Arrays, Strings, Pointers,
Structures, and Abstract Data
Types.

CO99. Investigate
various Linked Lists and
their implementations using
array and dynamic memory
allocation.

CO100. Implement Stack


Operations and evaluate
mathematical expressions
using stack.

CO101. Apply recursion, solve


various problems using
recursion, and analyze Linear &
Binary Search.

CO102. Explain and Compare


various sorting and searching
algorithms.

UNIT I: 9.00
Introduction to Data Structure: Information and meaning, Arrays (one, two and multi- dimensional), Row
major and column major form, representation of strings, allocation of storage and scope of variable,
String Processing, Pointers, Structures & unions. Algorithm definition and its characteristics, Abstract
data types, Order of Complexity: Big O notation.

UNIT II: 9.00


Linked list: Introduction to linked list, linked list as a data structure, creation, insertion and deletion of
nodes from a list, getnode and free node operations, concept of header nodes, array implementation of
lists and its limitation, Allocating and freeing dynamic memory, comparing dynamic and array
implementation of lists. Doubly Linked lists, Circular linked lists and Circular Double linked lists. C
implementation: Singly & circular linked lists,

UNIT III: 9.00


Stack: Definition, Primitive operations, representing stack in C, implementing the push and pop
operation, testing exceptional conditions, infix, postfix and prefix expression (definition and examples),
infix to postfix, evaluation of postfix expression (Algorithm and C implementation). Linked
implementation of stacks.

UNIT IV: 9.00


Recursion definition and processes, algorithms, recursion in C, Writing recursive programs (e.g. Factorial,
multiplication, Fibonacci sequence, Binary search, Towers of Hanoi Problem and similar problems),
Properties of recursive definition or Algorithms, Efficiency of recursion. Searching linear and Binary
Search.

UNIT V: 9.00
Queues: Introduction, Definition of Queue and its sequential representation, C implementation of
queues, insert and remove operation, Applications and Priority queues. Linked implementation of
queues, linked implementation of priority queue. Sorting: Exchange Sorts (Bubble sort, Quick sort),
Straight Selection sort, and Insertion sort.

ESSENTIAL READINGS:
1. Y. Langsam, M. J. Augenstein, A.M. Tenenbaum, “Data Structure using C, C++”, second edition,
Prentice Hall of India, 2012.
2. S. Lipschutz, “Data Structures”, Schaum’s outline series, Tata McGraw Hill Edition, 2015.

REFERENCES:
1. E. Horowitz and S. Sahani, “Fundamentals of Data Structures”, Galgotia Book source Pvt. Ltd, 2008
2. Robert L.Kruse, “Data Structures and Program Design”, Third edition, PHI

E-RESOURCES:
1. http://www.nptel.ac.in/video.php?subjectId=106105085.
2. http://lcm.csa.iisc.ernet.in/dsa/dsa.html.
3. http://freevideolectures.com/Course/2519/C-Programming-and-Data-Structures.
4. http://freevideolectures.com/Course/2279/Data-Structures-And-Algorithms

JOURNALS:
1. Arab Journal of Basic and Applied Sciences, https://www.tandfonline.com/toc/tabs20
2. Journal of the Brazilian Computer Society, https://journal-bcs.springeropen.com/

write s simple array program to insert 7 elements in the array with the help of user.

#include <stdio.h>

int main() {
int array[7];

printf("Enter 7 elements for the array:\n");


for (int i = 0; i < 7; i++) {
scanf("%d", &array[i]);
}

printf("Array elements:\n");
for (int i = 0; i < 7; i++) {
printf("%d ", array[i]);
}
printf("\n");

return 0;
}

C program that allows the user to insert a new value at the front of an array:

c
#include <stdio.h>

#define SIZE 10

int main() {
int array[SIZE];
int value;

printf("Enter %d elements for the array:\n", SIZE - 1);


for (int i = 1; i < SIZE; i++) {
scanf("%d", &array[i]);
}

printf("Enter the value to be inserted at the front: ");


scanf("%d", &value);

// Shift elements to the right


for (int i = SIZE - 1; i >= 1; i--) {
array[i] = array[i - 1];
}

// Insert the value at the front


array[0] = value;

printf("Array after inserting the value at the front:\n");


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

return 0;
}

C program that allows the user to insert a new value in the middle of an array:
#include <stdio.h>

#define SIZE 10

int main() {
int array[SIZE];
int value, position;

printf("Enter %d elements for the array:\n", SIZE - 1);


for (int i = 0; i < SIZE - 1; i++) {
scanf("%d", &array[i]);
}

printf("Enter the value to be inserted: ");


scanf("%d", &value);

printf("Enter the position where you want to insert the value (1-%d): ", SIZE - 1);
scanf("%d", &position);

// Shift elements to the right from the specified position


for (int i = SIZE - 1; i > position - 1; i--) {
array[i] = array[i - 1];
}
// Insert the value at the specified position
array[position - 1] = value;

printf("Array after inserting the value:\n");


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

return 0;
}

C program that allows the user to insert a new value at the last position of an array:

#include <stdio.h>

#define SIZE 10

int main() {
int array[SIZE];
int value;

printf("Enter %d elements for the array:\n", SIZE - 1);


for (int i = 0; i < SIZE - 1; i++) {
scanf("%d", &array[i]);
}

printf("Enter the value to be inserted at the last position: ");


scanf("%d", &value);

// Insert the value at the last position


array[SIZE - 1] = value;

printf("Array after inserting the value at the last position:\n");


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

return 0;
}

C programme insertion

#include <stdio.h>
#define MAX_SIZE 100

int main() {
int arr[MAX_SIZE];
int i, size, num, pos;

// Input the size of the array


printf("Enter the size of the array (max %d): ", MAX_SIZE);
scanf("%d", &size);

// Input array elements


printf("Enter the elements of the array: ");
for (i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}

// Input the number to be inserted


printf("Enter the number to be inserted: ");
scanf("%d", &num);

// Input the position at which the number should be inserted


printf("Enter the position (0 - based index) where the number should be inserted: ");
scanf("%d", &pos);

// Check if the position is valid


if (pos < 0 || pos > size) {
printf("Invalid position.\n");
} else {
// Shift the elements to the right from the given position
for (i = size - 1; i >= pos; i--) {
arr[i + 1] = arr[i];
}

// Insert the number at the given position


arr[pos] = num;
size++; // Increase the size of the array

// Print the resulting array


printf("Array after insertion: ");
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

return 0;
}
What is String?
n Data Structures and Algorithms (DSA), a String can also be defined as a
sequence of characters, stored in contiguous memory locations, terminated by a
special character called the null character ‘\0’.

Characteristics of String:

In the context of Data Structures and Algorithms, strings have the following
properties:
● Ordered: Strings are ordered sequences of characters, where each character
has a unique position in the string.
● Indexable: Strings can be indexed, meaning that individual characters within
a string can be accessed using a numerical index.
● Comparable: Strings can be compared to each other to determine their
relative order or equality.
Applications of String:
Strings are widely used in computer science and have many applications in
various fields, some of which are:
● Text Processing: Strings are used to represent and manipulate text data,
such as in text editors, word processors, and other applications that deal with
text.
● Pattern Matching: Strings can be searched for patterns, such as regular
expressions or specific sub-strings, to extract or process data in a specific
way.
● Data Compression: Strings can be compressed to reduce the amount of
storage required to store them. String compression algorithms, such as
Huffman coding and run-length encoding, are commonly used in data
compression applications.
Advantages of String:
● Widely Supported: Strings are a fundamental data type in most
programming languages, making them widely available and well-supported.
● Efficient Manipulation: Many algorithms and data structures have been
developed to efficiently manipulate strings, such as string matching
algorithms, string compression algorithms, and data structures like tries and
suffix arrays.
● Ability to Model Real-World Data: Strings are often used to model real-
world data, such as names, addresses, and other forms of text data, making
them a useful tool in many applications.
● Text Mining and Natural Language Processing: Strings are used as input
to algorithms for text mining and natural language processing, such as
sentiment analysis and named entity recognition.
To learn about more advantages refer to this article.
Disadvantages of String:
● Encoding Issues: Strings can be represented in different encodings, such as
UTF-8 or UTF-16, which can cause compatibility issues when processing
strings from different sources.
● Immutable: Strings are often implemented as immutable data structures,
meaning that once a string has been created, it cannot be modified. This can
lead to additional overhead when manipulating strings, as new strings must
be created for every modification.
● Slow Concatenation: Concatenating strings can be slow, as it requires
creating a new string and copying all of the characters from the original strings
into the new string.
Basic String Operations with
Implementation
In this post, we will look into some of the basic String operations such as:
● Accessing characters by index in a string.
● Inserting character into a String.
● Modifying character in String
● Deletion of Character in String
● Concatenating strings (combining multiple strings into one).
● Finding the length of a string
● Comparing strings for equality or lexicographical order
Let us consider the basic String operations one by one.
Accessing characters by index in a string.
To access any character in a String, we need:
1. A non-empty string (say “str”)
2. A position/index of the character from where it is to be accessed. (say “k”)
Using these two, the character can be easily accessed using the below syntax:

char ch = str[k];
OR
char ch = str.charAt(k);

CProgram

#include <stdio.h>
#include <string.h>

// Function to demonstrate accessing character by index


char accessCharByIndex(char* str, int k)
{
// Return the character at the kth index in the string
return str[k];
}

// Driver code
int main()
{
char str[] = "GeeksforGeeks ";
int k = 4;
printf("%c\n", accessCharByIndex(str, k));

return 0;
}
Inserting Character/String into an String.
To insert any Character/String in a String, we need:
1. A character/string that is to be inserted in the string (say “ch”)
2. A position/index of the Character/String where it is to be inserted. (say “k”)
Below is the implementation of the above approach:
#include <stdio.h>
#include <string.h>

void insertDemo(char* str, const char* ch, int k) {


int len1 = strlen(str);
int len2 = strlen(ch);

// Shift characters to the right to make space for ch


for (int i = len1; i >= k; i--) {
str[i + len2] = str[i];
}

// Insert ch at kth index of str


for (int i = 0; i < len2; i++) {
str[k + i] = ch[i];
}

printf("Modified String: %s\n", str);


}

int main() {
char str[] = "GeeksGeeks ";
char ch[] = "for";
int k = 5;

printf("Original String: %s\n", str);


insertDemo(str, ch, k);

return 0;
}

Modifying character in String


To modify any Character in a String, we need:
1. A character that is to replaced in the string (say “ch”)
2. A position/index of the Character where it is to be replaced at. (say “k”)
Below is the implementation of the above approach:
#include <stdio.h>
#include <string.h>

int main()
{
// Define the string
char str[] = "Geeks Gor Geeks";
// Define the index
int index = 6;

// Define the character


char ch = 'F';

// Print the original string


printf("Original String = %s\n", str);

// Modify the string


str[index] = ch;

// Print the modified string


printf("Modified String = %s\n", str);

return 0;
}

Deletion of character in String


To delete any Character in a String, we need:
● A character that is to deleted in the string (say “ch”)
Below is the implementation of the above approach:

#include <stdio.h>

#include <string.h>

void removeChar(char* s, char c) {

int i, j, n = strlen(s);

for (i = j = 0; i < n; i++) {

if (s[i] != c) {

s[j++] = s[i];

}
}

s[j] = '\0';

int main() {

char s[] = "geeksforgeeks";

removeChar(s, 'g');

printf("%s", s);

return 0;

Output
eeksforeeks

Concatenating strings (combining multiple strings into one).


To concatenate any String to a String, we need:
● A string that is to appended with the string (say “ch”)
Below is the implementation of the above approach:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>
int main()

char init[] = "this is init";

char add[] = " added now";

char* result = (char*)malloc(strlen(init) + strlen(add) + 1);

strcpy(result, init);

strcat(result, add);

printf("%s\n", result);

free(result);

return 0;

Output
this is init added now
Finding the length/size of a string
To find the length of the String, we need:
● A string for which the length/size is to be determined (say “str”)
Below is the implementation of the above approach:
#include <stdio.h>

#include <string.h>

int main() {

// String

char str[] = "GeeksforGeeks";

// Length of string using strlen() function

int length = strlen(str);

printf("%d\n", length);

return 0;

Output
13
Comparing Strings for Equality
To compare strings, Define a function to compare values with the following
conditions :
1. if (string1 != string2) it returns a False.
2. if both the strings are equal lexicographically (string1 == string2), it
returns True.
Below is the implementation of the above approach:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>

// This function compares two strings lexicographically


bool stringCompare(const char* str1, const char* str2) {
int l1 = strlen(str1);
int l2 = strlen(str2);
int lmin = (l1 < l2) ? l1 : l2;

for (int i = 0; i < lmin; i++) {


int str1_ch = (int)str1[i];
int str2_ch = (int)str2[i];

if (str1_ch != str2_ch) {
return false;
}
}

// Edge case for strings with different lengths


if (l1 != l2) {
return false;
}

// If none of the above conditions is true,


// it implies both the strings are equal
return true;
}

// Driver function to test the above program


int main() {
const char* string1 = "Geeksforgeeks";
const char* string2 = "Practice";
const char* string3 = "Geeks";
const char* string4 = "Geeks";

// Comparing string1 and string2


printf("Comparing %s and %s: %s\n", string1, string2,
stringCompare(string1, string2) ? "true" : "false");

// Comparing string3 and string4


printf("Comparing %s and %s: %s\n", string3, string4,
stringCompare(string3, string4) ? "true" : "false");

// Comparing string1 and string4


printf("Comparing %s and %s: %s\n", string1, string4,
stringCompare(string1, string4) ? "true" : "false");

return 0;
}
Output
Comparing Geeksforgeeks and Practice : false
Comparing Geeks and Geeks : true
Comparing Geeksforgeeks and Geeks : false

Applications, Advantages and


Disadvantages of String
● The String data structure is the backbone of programming languages and the
building blocks of communication. String data structures are one of the most
fundamental and widely used tools in computer science and programming.
They allow for the representation and manipulation of text and character
sequences in a variety of ways. The string data structure is a powerful tool
that can be used to store and process large amounts of text data, from simple
strings to complex sentences, paragraphs, and even entire books.
● It is a sequence of characters that represent text or other forms of data. It is a
fundamental data structure that is used in many programming languages to
store and manipulate text-based data. In most programming languages,
strings are implemented as an array of characters, with each character having
a unique index position within the array.

String Representation

Applications of String:
● Plagiarism Checker: Strings can be used to find Plagiarism in codes, and
contents in a very little amount of time using string matching algorithms. Using
this the computer could easily tell us the percentage of code, and text written
by any two users matches by how much percent.
● Encoding/Decoding(Cipher Text Generation): Strings can be used for
encoding and decoding for the safe transfer of data from sender to receiver to
make sure no one in the way of transmission gets to read your data as they
could perform both active and passive attacks. The text you transfer as a
message gets ciphered at the sender’s end and decoded at the receiver’s
end.
● Information Retrieval: String applications help us to retrieve information from
unknown data sources( large datasets used as input) along with the help of
string matching/retrieval module helps us to retrieve important information.
● Improved Filters For The Approximate Suffix-Prefix Overlap
Problem: Strings and its algorithms applications help us to provide improved
Filters for the Approximate Suffix-Prefix Overlap Problem. The approximate
suffix-prefix overlap problem is to find all pairs of strings from a given set such
that a prefix of one string is similar to a suffix of the other.
● Network communication: Strings are used to encode and decode data sent
over networks, such as HTTP requests and responses.
● File handling: Strings are used to manipulate file paths and names, and to
read and write files.
● Data analysis: Strings can be used to extract meaningful insights from large
amounts of text data, such as natural language processing and sentiment
analysis.
Real-Time Application of String:
● Spam Detection: Strings can be used to serve as a spam detection system
as the concept of string matching algorithm will be applied here. Spam
(unwanted emails) could cause great financial loss. All the spam filters use
the concept of string matching to identify and discard the spam.
● Bioinformatics: Strings can be used in the field of Bioinformatics( DNA
sequencing). String matching module can be used to solve issues or
problems regarding genetic sequences and to find the patterns in DNA.
● Intrusion Detection System: Strings can be used in intrusion detection
systems. Packets that contain intrusion related keywords are found by
applying string matching algorithms.
● Search Engines: Strings can be used in many search engine techniques.
Most of the data are available on the internet in the form of textual data. Due
to huge amount of uncategorized text data, it becomes really difficult to search
a particular content. Web search engines organize the data and to categorize
the data string matching algorithms are used.
Operations on String:
String provides users with various operations. Some of the important ones are:
● size(): This function is used to find the length of the string.
● substr(): This is used to find a substring of length a particular length starting
from a particular index.
● +: This operator is used to concatenate two strings.
● s1.compare(s2): This is used to compare two strings s1 and s2 to find which
is lexicographically greater and which one is smaller.
● reverse(): This function is used to reverse a given string.
● sort(): This function is used to sort the string in lexicographic order.
For more reference to operations on string refer to: C/C++ Operations On String
Advantages of String:
● Text Processing: Strings are used to represent text in programming
languages. They can be used to manipulate and process text in various ways,
such as searching, replacing, parsing, and formatting.
● Data Representation: Strings can be used to represent other data types,
such as numbers, dates, and times. For example, you can use a string to
represent a date in the format “YYYY-MM-DD”, or a time in the format
“HH:MM:SS”.
● Ease of Use: Strings are easy to use and manipulate. They can be
concatenated, sliced, and reversed, among other things. They also have a
simple and intuitive syntax, making them accessible to programmers of all skill
levels.
● Compatibility: Strings are widely used across programming languages,
making them a universal data type. This means that strings can be easily
transferred between different systems and platforms, making them a reliable
and efficient way to communicate and share data.
● Memory Efficiency: Strings are usually stored in a contiguous block of
memory, which makes them efficient to allocate and deallocate. This means
that they can be used to represent large amounts of data without taking up too
much memory.
Disadvantages of String:
● Memory Consumption: Strings can consume a lot of memory, especially
when working with large strings or many strings. This can be a problem in
memory-constrained environments, such as embedded systems or mobile
devices.
● Immutability: In many programming languages, strings are immutable,
meaning that they cannot be changed once they are created. This can be a
disadvantage when working with large or complex strings that require frequent
modifications, as it can lead to inefficiencies and memory overhead.
● Performance Overhead: String operations can be slower than operations on
other data types, especially when working with large or complex strings. This
is because string operations often involve copying and reallocating memory,
which can be time-consuming.
● Encoding and Decoding Overhead: Strings can have different character
encodings, which can lead to overhead when converting between them. This
can be a problem when working with data from different sources or when
communicating with systems that use different encodings.
● Security Vulnerabilities: Strings can be vulnerable to security vulnerabilities,
such as buffer overflows or injection attacks, if not handled properly. This is
because strings can be manipulated by attackers to execute arbitrary code or
access sensitive data.

You might also like