0% found this document useful (0 votes)
5 views77 pages

DSA Initial

The document provides an overview of data structures and algorithms, defining data structures as methods for organizing and storing data efficiently, with examples like arrays and linked lists. It discusses various types of data structures, including primitive and non-primitive, and outlines their operations such as searching, sorting, and insertion. Additionally, it covers concepts like time complexity, data types, and the importance of efficient data structure selection for program performance.

Uploaded by

nkarn5789
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)
5 views77 pages

DSA Initial

The document provides an overview of data structures and algorithms, defining data structures as methods for organizing and storing data efficiently, with examples like arrays and linked lists. It discusses various types of data structures, including primitive and non-primitive, and outlines their operations such as searching, sorting, and insertion. Additionally, it covers concepts like time complexity, data types, and the importance of efficient data structure selection for program performance.

Uploaded by

nkarn5789
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/ 77

Data Structures & Algorithms

What is Data Structure:

• A data structure is a storage that is used to store and organize data.


It is a way of arranging data on a computer so that it can be
accessed and updated efficiently.
What is Data Structure:

• Data Structures – These are like the ingredients you need to build efficient
algorithms. These are the ways to arrange data so that they (data items) can
be used efficiently in the main memory.
• Examples: Array, Stack, Linked List, and many more. You don't need to worry about
these names. These topics will be covered in detail in the upcoming tutorials.

• Algorithms – Sequence of steps performed on the data using efficient data


structures to solve a given problem, be it a basic or real-life-based
one. Examples include: sorting an array.
Some other Important terminologies:

• Database – Collection of information in permanent storage for faster


retrieval and updation.
• Examples are MySql, MongoDB, etc.

• Data warehouse – Management of huge data of legacy data (the data we


keep at a different place from our fresh data in the database to make the
process of retrieval and updation fast) for better analysis.

• Big data – Analysis of too large or complex data, which cannot be dealt with
the traditional data processing applications.
Memory Layout of C Programs:
• When the program starts, its code gets
copied to the main memory.
• The stack holds the memory occupied by
functions. It stores the activation records
of the functions used in the program. And
erases them as they get executed.
• The heap contains the data which is
requested by the program as dynamic
memory using pointers.
• Initialized and uninitialized data segments
hold initialized and uninitialized global
variables, respectively.
What is Data Structure & Algorithm:

• To structure the data in memory, 'n' number of algorithms were


proposed, and all these algorithms are known as Abstract data types.
• These abstract data types are the set of rules.
Types of Data Structures:
• There are two types of data structures:
Primitive data structure

Non-primitive data structure


Types of Data Structures:
Primitive Data structure
The primitive data structures are primitive data types.

The int, char, float, double, and pointer are the primitive data
structures that can hold a single value.
Types of Data Structures:
Non-Primitive Data structure
The non-primitive data structure is divided into two types:

Linear data structure

Non-linear data structure


Types of Data Structures:
Linear Data Structure
• The arrangement of data in a sequential manner is known as a linear
data structure.
• The data structures used for this purpose are Arrays, Linked list,
Stacks, and Queues.
• In these data structures, one element is connected to only one
another element in a linear form.
Types of Data Structures:
Non-Linear Data Structure
• When one element is connected to the 'n' number of elements known
as a non-linear data structure.
• The best example is trees and graphs.
• In this case, the elements are arranged in a random manner.
Classification of Data Structures:
Major Operations:
The major or the common operations that can be performed on the
data structures are:
• Searching: We can search for any element in a data structure.
• Sorting: We can sort the elements of a data structure either in an
ascending or descending order.
• Insertion: We can also insert the new element in a data structure.
• Updation: We can also update the element, i.e., we can replace the
element with another element.
• Deletion: We can also perform the delete operation to remove the
element from the data structure.
Advantages of Data structures:
The following are the advantages of a data structure:
• Efficiency: If the choice of a data structure for implementing a
particular ADT is proper, it makes the program very efficient in terms
of time and space.
• Reusability: The data structure provides reusability means that
multiple client programs can use the data structure.
• Abstraction: The data structure specified by an ADT also provides
the level of abstraction. The client cannot see the internal working of
the data structure, so it does not have to worry about the
implementation part. The client can only see the interface.
Advantages of Data structures:
The following are the advantages of a data structure:
• 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.
• Processor speed − Processor speed although being very high, falls
limited if the data grows to billion records.
• Multiple requests − As thousands of users can search data
simultaneously on a web server, even the fast server fails while
searching the data.
To solve the mentioned problems, data structures come to rescue.

Data can be organized in a data structure in such a way that all items may not
be required to be searched, and the required data can be searched almost
instantly.
Data structure Fundamentals:
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 Structure:
Correctness − 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.
Time Complexity and Big O Notation:
An analogy to a real-life issue:
• This morning I wanted to eat some pizza; So, I asked my brother to get me some from
Dominos, which is 3 km away.
• He got me the pizza, and I was happy only to realize it was too little for 29 friends who
came to my house for a surprise visit!
• My brother can get 2 pizzas for me on his bike, but pizza for 29 friends is too huge of an
input for him, which he cannot handle.
Time Complexity and Big O Notation:
What is Time Complexity?
Time Complexity is the study of the efficiency of algorithms. It tells us how
much time is taken by an algorithm to process a given input.

Consider two developers Shubham and Rohan, who created an algorithm


to sort ‘n’ numbers independently. When I made the program run for some
input size n, the following results were recorded:
Time Complexity and Big O Notation:
Time Complexity Calculation:
• In order to calculate the order(time complexity), the most impactful term
containing n is taken into account (Here n refers to Size of input). And the
rest of the smaller terms are ignored.
• Let us assume the following formula for the algorithms in terms of input
size n:
Time Complexity and Big O Notation:
What is a Big O?
• big O stands for ‘order of’
Execution Time Cases:
There are three cases which are usually used to compare various data
structure's execution time in a relative manner.

Worst Case − This is the scenario where a particular data structure


operation takes maximum time it can take. If an operation's worst case time
is ƒ(n) then this operation will not take more than ƒ(n) time where ƒ(n)
represents function of n.

Average Case − This is the scenario depicting the average execution time
of an operation of a data structure. If an operation takes ƒ(n) time in
execution, then m operations will take mƒ(n) time.

Best Case − This is the scenario depicting the least possible execution
time of an operation of a data structure. If an operation takes ƒ(n) time in
execution, then the actual operation may take time as the random number
which would be maximum as ƒ(n).
Data Definition:
Data Definition defines a particular data with the following
characteristics.
• Atomic − Definition should define a single concept.

• Traceable − Definition should be able to be mapped to some data


element.

• Accurate − Definition should be unambiguous.

• Clear and Concise − Definition should be understandable.


Data type:
Data type is a way to classify various types of data such as integer,
string, etc. which determines the values that can be used with the
corresponding type of data, the type of operations that can be
performed on the corresponding type of data. There are two data
types −

• Built-in Data Type

• Derived Data Type


Data type:
Built-in Data Type
Those data types for which a language has built-in support are known
as Built-in Data types. For example, most of the languages provide the
following built-in data types.
• Integers
• Boolean (true, false)
• Floating (Decimal numbers)
• Character and Strings
Data type:
Derived Data Type
• Those data types which are implementation independent as they can
be implemented in one or the other way are known as derived data
types.
• These data types are normally built by the combination of primary or
built-in data types and associated operations on them. For example −
Array
List
Stack
Queue
ARRAYS
a collection of same type data
ARRAYS
 An array is a collection of elements of the same type that
are referenced by a common name.
 Compared to the basic data type (int, float & char) it is
an aggregate or derived data type.
 All the elements of an array occupy a set of contiguous
memory locations.
 Why need to use array type?
 Consider the following issue:

"We have a list of 1000 students' marks of an


integer type. If using the basic data type (int),
we will declare something like the following…"

int studMark0, studMark1, studMark2, ..., studMark999;


ARRAYS
 Can you imagine how long we have to write
the declaration part by using normal variable
declaration?

int main(void)
{
int studMark1, studMark2, studMark3,
studMark4, …, …, studMark998, stuMark999,
studMark1000;


return 0;
}
ARRAYS
 By using an array, we just declare like this,

int studMark[1000];

 This will reserve 1000 contiguous memory locations for storing the
students’ marks.
 Graphically, this can be depicted as in the following figure.
ARRAYS
 This absolutely has simplified our declaration of the
variables.
 We can use index or subscript to identify each
element or location in the memory.
 Hence, if we have an index of jIndex,
studMark[jIndex] would refer to the jIndexth
element in the array of studMark.
 For example, studMark[0] will refer to the first
element of the array.
 Thus by changing the value of jIndex, we could refer
to any element in the array.
 So, array has simplified our declaration and of course,
manipulation of the data.
ARRAYS
One Dimensional Array: Declaration

 Dimension refers to the array's size, which is how big the


array is.
 A single or one dimensional array declaration has the
following form,
array_element_data_type array_name[array_size];

 Here, array_element_data_type define the base type of


the array, which is the type of each element in the array.
 array_name is any valid C / C++ identifier name that obeys
the same rule for the identifier naming.
 array_size defines how many elements the array will hold.
ARRAYS
 For example, to declare an array of 30 characters, that
construct a people name, we could declare,
char cName[30];
 Which can be depicted as follows,

 In this statement, the array character can store


up to 30 characters with the first character
occupying location cName[0] and the last
character occupying cName[29].
 Note that the index runs from 0 to 29. In C, an
index always starts from 0 and ends with array's
(size-1).
 So, take note the difference between the array
size and subscript/index terms.
ARRAYS
 Examples of the one-dimensional array declarations,
int xNum[20], yNum[50];
float fPrice[10], fYield;
char chLetter[70];

 The first example declares two arrays named xNum and yNum of type int. Array
xNum can store up to 20 integer numbers while yNum can store up to 50
numbers.
 The second line declares the array fPrice of type float. It can store up to 10
floating-point values.
 fYield is basic variable which shows array type can be declared together with
basic type provided the type is similar.
 The third line declares the array chLetter of type char. It can store a string up
to 69 characters.
 Why 69 instead of 70? Remember, a string has a null terminating character (\0)
at the end, so we must reserve for it.
ARRAYS
Array Initialization

 An array may be initialized at the time of declaration.


 Giving initial values to an array.
 Initialization of an array may take the following form,
type array_name[size] = {a_list_of_value};
 For example:
int idNum[7] = {1, 2, 3, 4, 5, 6, 7};
float fFloatNum[5] = {5.6, 5.7, 5.8, 5.9, 6.1};
char chVowel[6] = {'a', 'e', 'i', 'o', 'u', '\0'};
 The first line declares an integer array idNum and it immediately
assigns the values 1, 2, 3, ..., 7 to idNum[0], idNum[1],
idNum[2],..., idNum[6] respectively.
 The second line assigns the values 5.6 to
fFloatNum[0], 5.7 to fFloatNum[1], and so on.
 Similarly the third line assigns the characters 'a' to chVowel[0], 'e' to
chVowel[1], and so on. Note again, for characters we must use the
single apostrophe/quote (') to enclose them.
 Also, the last character in chVowel is NULL character ('\0').
ARRAYS
 Initialization of an array of type char for holding strings may take the following form,

char array_name[size] = "string_lateral_constant";

 For example, the array chVowel in the previous example could have been written
more compactly as follows,

char chVowel[6] = "aeiou";

 When the value assigned to a character array is a string (which must be enclosed in
double quotes), the compiler automatically supplies the NULL character but we still
have to reserve one extra place for the NULL.
 For unsized array (variable sized), we can declare as follow,

char chName[ ] = "Mr. India";

 C compiler automatically creates an array which is big enough to hold all the
initializer.
Q: Largest Element in an array
Q: Largest Element in an array
ARRAYS
 Arrays allow programmers to group related items of the same
data type in one variable.
 However, when referring to an array, one has to specify not only
the array or variable name but also the index number of interest.
 Program example 1: Sum of array’s element.
 Notice the array's element which is not initialized is set to 0
automatically.
ARRAYS
 Program example 2: Searching the smallest value.
 Finding the smallest element in the array named fSmallest.
 First, it assumes that the smallest value is in fSmallest[0] and
assigns it to the variable nSmall.
 Then it compares nSmall with the rest of the values in fSmallest,
one at a time.
 When an element is smaller than the current value contained in
nSmall, it is assigned to nSmall. The process finally places the
smallest array element in nSmall.
ARRAYS
 Program example 3: Searching the biggest
value. By modifying the previous example we
can search the biggest value.
ARRAYS
Two Dimensional/2D Arrays

 A two dimensional array has two subscripts/indexes.


 The first subscript refers to the row, and the second, to the column.
 Its declaration has the following form,
data_type array_name[1st dimension size][2nd dimension size];

 For examples,
int xInteger[3][4];
float matrixNum[20][25];

 The first line declares xInteger as an integer array with 3 rows and
4 columns.
 Second line declares a matrixNum as a floating-point array with 20
rows and 25 columns.
ARRAYS
 If we assign initial string values for the 2D array it will look
something like the following,

char Name[6][10] = {"Mr. Bean", "Mr. Bush", "Nick",


"Kidman", "Arnold", "Jodie"};

 Here, we can initialize the array with 6 strings, each with


maximum 9 characters long.
 If depicted in rows and columns it will look something like the
following and can be considered as contiguous arrangement in
the memory.
ARRAYS
 Take note that for strings the null character (\0) still needed.
 From the shaded square area of the figure we can determine the size of the
array.
 For an array Name[6][10], the array size is 6 x 10 = 60 and equal to the
number of the colored square. In general, for

array_name[x][y];

 The array size is = First index x second index = xy.


 This also true for other array dimension, for example three dimensional
array,

array_name[x][y][z]; => First index x second index x third index = xyz


 For example,

ThreeDimArray[2][4][7] = 2 x 4 x 7 = 56.

 And if you want to illustrate the 3D array, it could be a cube with wide, long
and height dimensions.
Matrix Multiplication
Matrix Multiplication
Matrix Multiplication
Matrix Multiplication
Matrix Multiplication
Matrix Multiplication
Algorithm of Matrix Multiplication
1. Start.
2. Enter the value of m and n (or) order of the first matrix.
3. Enter the value of p and q (or) order of the second matrix.
4. Create a matrix of size a[m][n] and b[p][q].
5. Enter the element of matrices row wise using loops.
6. If a number of columns of first matrix is not equal to the number of rows of second matrix,
print matrix multiplication is not possible and exit. If not, proceed to next step.
7. Create a third matrix, c of size m x q to store the product.
8. Set a loop from i=0 to i=m.
9. Set an inner loop for the above loop from j=0 to j=q.
10. Initialize the value of element (i, j) of new matrix to 0.
11. Set an inner loop inside the above loop from k=0 to k=p.
12. Using the add and assign operator (+=) store the value of a[i][k] * b[k][j] in the third matrix,
c[i][j].
13. Print the third matrix.
14. Stop.
Flow chart of Matrix Multiplication
End-of-C-arrays

You might also like