0% found this document useful (0 votes)
1 views

Data Structures Notes_063611

The document outlines the SWDDA 401 module on Data Structure and Algorithm Fundamentals at Glory Academy, focusing on applying these concepts using JavaScript. It covers essential topics such as number systems, data structures, and algorithm implementation, with a total of 150 learning hours. The module aims to equip learners with the skills to effectively convert between number systems and implement algorithms using JavaScript.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Data Structures Notes_063611

The document outlines the SWDDA 401 module on Data Structure and Algorithm Fundamentals at Glory Academy, focusing on applying these concepts using JavaScript. It covers essential topics such as number systems, data structures, and algorithm implementation, with a total of 150 learning hours. The module aims to equip learners with the skills to effectively convert between number systems and implement algorithms using JavaScript.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 111

SWDDA 401: DATA STRUCTURE AND ALGORITHM FUNDAMENTALS

Competency: Apply Data Structure and Algorithm Fundamentals Using Java Script

School: GLORY ACADEMY

Class: level 4 SWD

Module name: SWDDA 401 DATA STRUCTURE AND


ALGORITHM FUNDAMENTALS

Competency: Apply Data Structure and Algorithm Fundamentals

Using Java Script Learning Hours: 150


TRAINER: YANKURIJE Gad

Elements of Competence and Performance Criteria

Elements of Performance criteria


competence

1. Apply 1.1 Number systems are correctly converted according to the base
Algorithm conversion methods
Fundamental
s 1.2 Logic gates and expressions are well described based on boolean algebra

1.3 Data types are effectively used according to their intended use

1.4 Operators are appropriately used based on datatype

1.5 Algorithm is properly written based on problem to be solved

2.1 Data structure concepts are clearly identified based on intended use.
2. Apply Data
Structure
2.2 Linear Data Structures are properly applied based on their operational
complexity
2.3 NonLinear Data Structures are properly applied based on their
operational complexity

3.1 JavaScript Source code is properly developed based on Algorithm

3. Implement
3.2 JavaScript source code is successfully run in accordance with expected
Algorithm using
result
JavaScript

3.3 Time and space complexity are successfully tested based on data
structure standards

Learning outcome 1: Apply Algorithm Fundamentals

Learning outcomes: At the end of the module the learner will be able to:

• Apply Algorithm Fundamentals


• Apply Data Structure
• Implement Algorithm using JavaScript
Data structures: a way of storing and organizing data in the computer memory
so that it can be processed efficiently.
An algorithm is a sequence of steps executed by a computer that takes an input
and transforms it into a target output. Together, data structures and algorithms
combine and allow programmers to build whatever computer programs would
like.
• Number systems are correctly converted according to the base
conversion methods

Conversion of base numbers


• Description of key concepts
Decimal base: A Decimal number system is the number system
that we use on a daily basis based on the 10 digits. Decimal number
system is the number system we use every day and uses digits from
0 - 9 i.e. 0, 1, 2, 3, 4, 5, 6, 7, 8, & 9. The base number of the decimal
number system is 10 as the total number available in this number
system is 10.

Binary base: It describes numeric values by two separate


symbols; 1 (one) and 0 (zero).
Hexadecimal base: Hexadecimal is a numbering system with
base 16. It can be used to represent large numbers with fewer
digits.
In this system there are 16 symbols or possible digit values from 0 to
9, followed by six alphabetic characters -- A, B, C, D, E and F.
These characters are used to represent decimal values from 10 to 15
in single bits.

Here's what the decimal and hexadecimal systems look like for digits 0 to 15.

Decimal 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Hexadecimal 0 1 2 3 4 5 6 7 8 9 A B C D E F

Octal base has a base of eight and uses the numbers from 0 to 7.
The octal numbers, in the number system, are usually represented by
binary numbers when they are grouped in pairs of three. For
example, an octal number 128 is expressed as 0010102 in the binary
system, where 1 is equivalent to 001 and 2 is equivalent to 010.

Octal Number System

Base – 8

Octal Symbol – 0, 1, 2, 3, 4, 5, 6 and 7


• Number system from decimal base to:

Binary base and vice versza

To convert numbers from decimal to binary, the given decimal number is


divided repeatedly by 2 and the remainders are noted down till we get 0 as the
final quotient. The following steps is considered as the decimal to binary
formula that shows the procedure of conversion.
• Step 1: Divide the given decimal number by 2 and note down the remainder.
• Step 2: Now, divide the obtained quotient by 2, and note the remainder again.
• Step 3: Repeat the above steps until you get 0 as the quotient.
• Step 4: Now, write the remainders in such a way that the last
remainder is written first, followed by the rest in the reverse order.
• Step 5: This can also be understood in another way which states
that the Least Significant Bit (LSB) of the binary number is at the
top and the Most Significant Bit (MSB) is at the bottom. This
number is the binary value of the given decimal number.
Let us understand this with an example.
Example: Convert the decimal number 1310 to binary.

Solution: We will start dividing the given number (13) repeatedly by 2


until we get the quotient as 0. We will note the remainders in order.

Division by 2 Quotient Remainder

13 ÷ 2 6 1 (LSB)

6÷2 3 0

3÷2 1 1

1÷2 0 1 (MSB)
After noting the remainders, we will write them in such a way that the Most
Significant Bit (MSB) of the binary number is written first, followed by the
rest. Therefore, the binary equivalent for the given decimal number 1310 is
11012. This means that 1310 = 11012.
Decimal to Binary Table

There are different methods of converting numbers from decimal to binary.


When we convert numbers from decimal to binary, the base of the number
changes from 10 to 2. It should be

noted that all decimal numbers have their equivalent binary numbers. The
following table shows the decimal to binary chart of the first 20 whole
numbers.
Decimal Numbers Binary Numbers

0 0

1 1

2 10

3 11

4 100

5 101

6 110

7 111

8 1000
9 1001

10 1010

11 1011

12 1100

13 1101

14 1110

Decimal Numbers Binary Numbers

15 1111

16 10000

17 10001

18 10010

19 10011

20 10100

Examples
1: Convert 17410 to binary.
2: Convert the following decimal number into binary number: 156
3: State true or false with reference to decimal to binary conversion.

a.) The binary number system has a base of 2 since it uses only two digits
to represent a number.
b.) When the decimal number 10 is converted to binary, it gives the
value as 1010. c.) When the decimal number 4 is converted to binary,
it gives the value as 100.
Solution:

a.) True, the binary number system has a base of 2 since it uses only two digits
to represent a number.

b.) True, when the decimal number 10 is converted to binary, it gives the
value as 1010. c.) True, when the decimal number 4 is converted to binary,
it gives the value as 100.
Binary to Decimal Conversion Methods

There are two main methods for converting binary number systems into
decimal number systems. These methods are:

• Positional Notation

• Doubling
Conversion Using Positional Notation

• Write the binary number and count the power of 2 from right to
left, starting from 0 onwards.
• Now each binary number has the corresponding power of 2
starting from right to left. So the most significant bit will have the
highest power of 2.
• Add the product of the second step
• The final answer will be converted into a decimal number that is base 10.
Example of Positional Notation

Binary Number: (101)2

1 0 1

1 x 22 + 0 x 21 + 1 x 20

4+0+1

(5)10
So, the decimal number of (101)2 is (5)10

Similar we can represent fractional binary number

into decimals Binary Number: (0.101)2


1 0 1.1 0 1

1 x 22 + 0 x 21 + 1 x 20 . 1 x 2-1 + 0 x 2-2 + 1 x 2-3

(4 + 0 + 1) . (0.5 + 0 + 0.125)

(5.625)10

So, the decimal number of (0.101)2 is (5.625)10

Conversion Using Doubling

Conversion using doubling is one of the simplest ways for converting binary
numbers into decimal numbers. We need to take the most signification bit or
leftmost digit of the number. Then multiply the digit by 2 and add the second
leftmost bit and store the result. Similarly, we need to take the result and
multiply it by 2 and take the third leftmost bit and update the result. This
process will continue till we reach the least significant bit which is the
rightmost bit. Since we are multiplying by 2 so this process is known as
Doubling.

Example of Doubling
Binary Number: (101)2

=1

=1x2+0=2

=2x2+1=5
So, the decimal number of (101)2 is (5)10

Binary to Decimal Formula

The formula to convert binary number system into decimal can be

represented by, A = xn * bn + xn-1 * bn-1 + ….. + x1 * b1 + x0 * b0


Where,

A represents the integer

x represents the digit value

b represents the base value

For Example :

(1000)2 = 1 x 23 + 0 x 22 + 0 x 21 + 0 x 20

Tabular Representation of Binary to Decimal Number

Binary1 Decimal1 Binary2 Decimal2

0000 0 1000 8

0001 1 1001 9

0010 2 1010 10

0011 3 1011 11
0100 4 1100 12

0101 5 1101 13

0110 6 1110 14

0111 7 1111 15

How to Convert Decimal to Octal Number?

To convert a decimal number to an octal number, there are several direct


and indirect methods. They are as given below:

• Decimal to Octal Conversion Using by Direct Method: As the name


suggests decimal numbers are directly converted to octal numbers.
• Decimal to Octal Conversion Using by Indirect Method: This method
converts the decimal number into a binary number or hexadecimal first
and then converts that to an octal number.

Decimal to Octal Conversion Using Direct Method

To convert a Decimal number to an Octal number directly, you must start


dividing the number by 8 until you get 0 as the quotient. This is a
straightforward method that involves dividing the number to be converted.

Step 1: If the decimal number is N, divide it by 8 because the octal number


system’s base is 8.

Step 2: Note the value of the residual, which will be one of the following: 0, 1,
2, 3, 4, 5, 6, or 7. Divide the remaining decimal number until it equals 0 and
record the remainder of each step.

Step 3: Then, from bottom to top (or in reverse order), write the remainders,
which will be the equivalent octal number of the provided decimal number.
Let’s see this with the help of an example:

Note: The dividend (here given decimal number) is the number to be


divided, the divisor (here base of octal, i.e., 8) is the number to be divided
by, and the quotient (remaining divided decimal number) is the outcome of
the division.

Decimal to Octal Conversion Using Indirect Method

As mentioned above this method converts the decimal number into a binary
number or hexadecimal first and then converts that binary or hexadecimal
number to an octal number.

Convert Decimal to Binary to Octal

Let’s see how to convert decimal numbers to binary to octal conversion


HYPERLINK "https://testbook.com/maths/binary-to-octal-conversion"
HYPERLINK "https://testbook.com/maths/binary-to-octal-conversion"
HYPERLINK "https://testbook.com/maths/binary-to-octal-conversion". By
repeatedly dividing a number by two and recording the result, decimal values
can be transformed into binary.

Conversion of Integral

Decimal Numbers Step 1:

Divide the number by 2.


Step 2: Get the integer quotient for the next iteration.

Step 3: Get the remainder for the binary digit.

Step 4: Repeat the above steps until the quotient

is equal to 0. Take a look at an example to see

how this works.


The remainders are to be read from bottom to top to obtain the

binary equivalent. 4310=1010112

A binary number can be converted to an octal number in a variety of ways.


Direct and indirect approaches can both be used to convert. To begin, you must
convert a binary into a different base system (e.g., into decimal, or into
hexadecimal). After that, you must convert it to an octal number.

Because the octal number system has only eight digits (from 0 to 7), we may
express each octal digit using only three bits, as seen below.

Octal Digit Value Binary Equivalent

0 000

1 001

2 010

3 011

4 100

5 101

6 110

7 111

The process to convert a binary number to an octal number is as follows:

Step 1: Consider the binary number. For the integer component, divide the
binary digits into three groups (beginning from the right), and for the fraction
part, start from the left.
Step 2: Each set of three binary digits should be converted to

one octal digit. Let’s see with the help of an example.


Convert binary number 1010111100 into an octal number.

Therefore, Binary to octal is

= (1010111100)

= (001 010 111 100)

= (1 2 7 4)

= (1274)

Convert Decimal to Hexadecimal to Octal

Let’s see how to convert decimal numbers to hexadecimal to octal.

Converting with Remainders (for the integer part)

This is a simple procedure that involves dividing the number to be transformed by two.

Step 1: If the decimal number is N, divide it by 16 because the hexadecimal


number system’s base is 16. Make a note of the value of the remainder, which
will range from 0 to 15 (replace 10, 11, 12, 13, 14, 15 with A, B, C, D, E, and F
respectively). Divide the remaining decimal number until it equals 0 and record
the remainder of each step. Then, from bottom to top (or in reverse order), write
the remainders, which will be the equivalent hexadecimal number of the supplied
decimal number.

Example:

Converting with Division

This approach works by estimating a decimal number’s hexadecimal equivalent.


Any decimal number can be used as a starting point. Make a list of 16’s abilities.
Multiply the decimal number by the 16th power. Find the rest of the items.
Multiply the residual by the 16th power. Repeat until you’ve figured out the
whole solution.
Example:

Now we will convert hexadecimal number to octal number. Here are the steps:

Step 1: To begin, count the digits in the number.

Step 2: If n is the digit’s position from the right end, multiply each digit by 16n−116n−1.

Step 3: After you’ve multiplied the terms, add them together. The comparable
decimal form is the resultant.

Step 4: Write down the rest of the information.

Step 5: With the quotient, repeat the previous two steps until the quotient is zero.
Reverse the order of the remainder. The obtained number corresponds to the
desired outcome.

Example:

Convert Decimal to Octal including Decimal Point

To convert Decimal to Octal including decimal points, we first convert it to


hexadecimal and then convert it to octal.

Here’s how we convert to hexadecimal.

Converting with Remainders (for fractional part)

If the decimal fractional portion is M, multiply it by 16 because the


hexadecimal number system’s base is 16. Take note of the integer part’s
value, which will range from 0 to 15. (replace 10, 11, 12, 13, 14, and 15 by
A, B, C, D, E, and F respectively). Multiply the remaining decimal
fractional number until it equals 0 and record each integer part of the result.
Then write the integer part’s results, which will be a fraction hexadecimal
number comparable to the specified decimal value.

Once we get the hexadecimal number we convert it to octal using the steps
we discussed above.

Solved Examples of Decimal to Octal Conversion

Let’s see some more solved examples from decimal to Octal.


Example 1: Convert 44010 in octal.

Solution: We divide the number 440 by 8 till we get the quotient 0.

Division Quotient Reminder

4330/8 541 2

541/8 67 5

67/8 8 3

8/8 1 0

1/8 0 1

We read the reminder in reverse order. So 44010=103528 44010=103528

Example 2: What is the number 4321.35610 in the octal number system? (till 6 significant
digits)

Solution: In order to convert 4321.35610 into octal, we divide it into two parts
of whole number and fraction. First, let’s convert the whole number part. We
divide the number 4321 by 8 till we get the quotient 0.

Division Quotient Reminder

4321/8 540 1

540/8 67 4
67/8 8 3

8/8 1 0

1/8 0 1

We read the reminder in reverse order. So 44010=14352844010=143528.


Next is the conversion of the fraction part. If the decimal fractional
component is M, multiply it by 8 because the octal number system’s base is
8; till the significant digits are required.

— Octal

0.356 x 8 = 12.848 2

0.848 x 8 = 6.784 6

0.784 x 8 = 6.272 6

0.272 x 8 = 2.176 2

0.176 x 8 = 1.408 1

0.408 x 8 = 3.264 3

We have reached 6 significant digits. So we stop here. So 440.35610=14352.2662138

Decimal to Hexadecimal Conversion With Steps

Go through the steps given below to learn how to convert the numbers from decimal to hex.

Step 1: First, divide the decimal number by 16, considering the number as an integer.

Step 2: Keep aside the remainder.

Step 3: Again divide the quotient by 16 and repeat till you get the quotient
value equal to zero.

Step 4: Now take the values of the remainder’s left in the reverse
order to get the hexadecimal numbers.

Note: Remember, from 0 to 9, the numbers will be counted as the same in the
decimal system. But from 10 to 15, they are expressed in alphabetical order such
as A, B, C, D, E, F and so on.

Let us take an example to understand the steps given above for decimal to hex conversion.

Example: Convert (960)10 into

hexadecimal. Solution:
To convert decimal to hex, i.e. 960 base 10 to a hexadecimal number, follow the
steps given below:

Step 1: First, divide 960 by 16.


960 ÷ 16 = 60 and remainder = 0

Step 2: Again, divide quotient 60 by 16.


60 ÷ 16 = 3 and remainder 12.

Step 3: Again dividing 3 by 16, will leave quotient=0 and remainder = 3.

Step 4: Now taking the remainder in reverse order and substituting


the equivalent hexadecimal value for them, we get,
3→3, 12→C and 0→0

Therefore, (960)10 = (3C0)16

Number system from hexadecimal base to:

How to Convert Octal to Binary

We can convert a number from octal to binary using two ways:

• Indirect Method: Octal to decimal followed by decimal to binary


• Direct Method: Converting an octal number directly into the
binary number system
Indirect Method: Octal to Decimal to Binary

Let’s discuss the octal to binary conversion steps for the indirect method.

Step 1: Convert octal to decimal.


To convert octal to decimal, we multiply each digit by the power of 8 based on
the position starting from the right. We will multiply the first digit from the
right by 80. Next, we will multiply the second digit by 81 and so on.

Step 2: Convert decimal to binary.

For converting decimal to binary, we will divide the given number by 2 and record
the quotient and reminder. We will repeat the process until we obtain 0 as the quotient.

Example: Convert from octal to

binary: 548. Step 1: Octal to

decimal
548=4×80+5×81

548=4×1+5×8

548=4+40

548=4410

Step 2: Decimal to binary

Division Quotient Remainder

44÷2 22 0

22÷2 11 0

11÷2 5 1
5÷2 2 1

2÷2 1 0

1÷2 0 1

On arranging all the remainders in the reverse order, we will obtain the
following binary number:

Thus, 4410=1011002

Direct Method: Octal to Binary Conversion Using the Chart

There is no specific octal to binary formula for conversion. However, if you are
looking for an easier and less complicated octal to binary conversion method,
the direct method involves the following steps:

In octal to binary conversion, each digit in the octal number has a three-digit
binary representation. Using it, we can easily convert a number from octal to
binary. We can convert

octal to binary by choosing the binary equivalent of every digit of the octal
number from the below-mentioned chart.

Octal to Binary Conversion Table

The following table includes the octal numbers 0 to 7 and their equivalent
three-digit binary representation to aid octal to binary conversion.

Octal Number Equivalent Three-digit Binary Representation

0 000
1 001

2 010

3 011

4 100

5 101

6 110

7 111

Let’s convert 548 to binary.

The number 54 has two digits: 5 and 4.

From the above chart, we will note down their binary

equivalents. 5→101
4→100

Now, combining the two, we get the following binary number: 1011002.

Octal to Binary Conversion without Using the Conversion Table

Let’s understand the steps with the help of an example. We will also
understand how the three-digit binary representation is obtained for each
octal digit.
Example: Convert 7658 to binary.

Step 1: Write the octal number by separating the digits.

7 6 5

Step 2: Each octal digit represents 3 binary bits. Starting from right to left, the
value of these three digits is 20=1,21=2, and 22=4 respectively. Thus, write (4,
2, 1) below each octal digit.

7 6 5

4 2 1 4 2 1 4 2 1

Step 3: Identify the numbers among 4, 2, and 1 (powers of 2), which add up to
the octal number written on the top. Write 1 below if the number is used. Write 0
below the number that is not used in the sum. For example, 7=4+2+1, so we
write 1 under all the three numbers.

7 6 5

4 2 1 4 2 1 4 2 1

1 1 1 1 1 0 1 0 1

Step 4: Write the 1s and 0s from left to write to find the binary equivalent of
the given octal number.

Thus, 7658=1111101012
Octal to Binary Conversion: Examples

Let’s look at some examples based on all the methods

we learned. Example 1: Find the binary equivalent

of the octal number 348. Octal to decimal:


348=(3×81)+(4×80)

348=24+4

348=2810

Octal to Hexadecimal Conversion Table

Octal numbers converted to their corresponding hexadecimal values

Octal number Hexadecimal number


0 0
1 1
2 2
3 3
4 4

5 5
6 6
7 7
10 8
11 9
12 A
13 B
14 C
15 D
16 E
17 F
20 10

Solved Examples of Octal to

Hexadecimal Problem : 1
What is the hexadecimal equivalent of (50)8

Solution:

Octal is first converted to binary before being converted to hexadecimal.


Looking at the table of the octal to binary conversion,

5 = 101

1 =000
(50)8=(101000)2

As we can see from the binary to hexadecimal

conversion table, 0010 = 2


1000 = 8

As the result the hexadecimal equivalent of (50)8=(28)16

Problem : 2
Covert the octal number (56)8 to a hexadecimal number.

Solution:

Fist convert (56)8 into binary

number (56)8
= (101)(110)
=(101110)2

Now convert (101110)2 in

hexadecimal (101110)2
= (10)(1110)

= (2)(14)

= (2E)16

Problem: 3
Covert the octal (36.125)8 to Decimal Conversion

Solution:

= 3×81+6×80+1×8−1+2×8−2+5×8−3

= 24 + 6 + 0.125 + 0.03125 + 0.009765625

= (30.16601563)10(30.16601563)10

Decimal number =(30.16601563)10

Application of number base arithmetic operation

It is safe and wise to agree that number system holds its importance for
everything which includes proportion and percentage. Number system plays a
crucial role, both in our everyday lives and the technological world. With its
myriad qualities, it simplifies our lives a lot, which has been discussed as
follows:

• It enables to keep count of all the things around people. Like how
many apples are in the basket, or the number of milk cartons to be
purchased, etc.
• It enables the unique and accurate representation of different types of numbers.
• Making a phone call is possible only because we have a proper
and efficient number system.
• Elevators used in public places also depend upon number
systems for their functioning.
• Computation of any kind of interest on amounts deposited in banks.
• Creation of passwords on computers, security purposes.
• Encrypting important data, by converting figures into another
number system to avoid hacking and misuse of data.
• It enables easy conversion of numbers for technical purposes.
• The entirety of computer architecture depends upon number
systems (octal, hexadecimal). Every fiber of data gets stored in
the computer as a number.
Description of logic gates

• Representation of Boolean logic gates

Logic gates are an important concept if you are studying electronics. These are
important digital devices that are mainly based on the Boolean function. Logic
gates are used to carry out logical operations on single or multiple binary
inputs and give one binary output. In simple terms, logic gates are the
electronic circuits in a digital system.
AND gate

In the AND gate, the output of an AND gate attains state 1 if and only if all the
inputs are in state 1.

The Boolean expression of AND gate is Y = A.B

The truth table of a two-input AND basic gate is given as

A B Y
0 0 0
0 1 0
1 0 0
1 1 1
NAND gate

This basic logic gate is the combination of AND and NOT gates.

The

Boolean expression of the

NAND gate is The truth table of


NOT gate is as follows
A Y
0 1
1 0
OR gate

In an OR gate, the output of an OR gate attains state 1 if one or more inputs attain state 1.

The Boolean expression of the OR gate is Y = A + B, read as Y

equals A ‘OR’ B. The truth table of a two-input OR basic gate is

given as
A B Y
0 0 0
0 1 1
1 0 1
1 1 1
NOR gate
The NOR gate is a combination OR gate followed by an inverter. Its output is
"true" if both inputs are "false." Otherwise, the output is "false."

The truth table of a two-input OR basic gate is given as

A B Y
0 0 0
0 1 1
1 0 1
1 1 1
XOR gate
In an XOR gate, the output of a two-input XOR gate attains state 1 if one adds
only input and attains state 1.

The Boolean

expression of the XOR gate is

The truth table of an XOR gate

is
A B Y
0 0 0
0 1 1
1 0 1
1 1 0

Exclusive-NOR Gate (XNOR Gate)

In the XNOR gate, the output is in state 1 when both inputs are the same, that
is, both 0 or both 1.

The Boolean expression of the


XNOR gate

The truth table of an XNOR gate is given below

A B Y
0 0 1
0 1 0
1 0 0
1 1 1

What is the Easiest Way to Learn Logic Gates?

The easiest way to learn the function of basic logic gates is explained below.

• For AND Gate – If both the inputs are high then the output is also high
• For OR Gate – If a minimum of one input is high then the output is High
• For XOR Gate – If the minimum one input is high then only the output is high
• NAND Gate – If the minimum one input is low then the output is high
• NOR Gate – If both the inputs are low then the output is high.

Applications of Logic Gates

Circuits

De-Morgan's First Theorem

According to the first theorem, the complement result of the AND operation is
equal to the OR operation of the complement of that variable. Thus, it is
equivalent to the NAND function and is a negative-OR function proving that
(A.B)' = A'+B' and we can show this using the following table.

Inputs Output For Each Term

A B A.B (A.B)' A' B' A'+B'

0 0 0 1 1 1 1

0 1 0 1 1 0 1

1 0 0 1 0 1 1

1 1 1 0 0 0 0
De-Morgan's Second Theorem

According to the second theorem, the complement result of the OR operation is


equal to the AND operation of the complement of that variable. Thus, it is the
equivalent of the NOR function and is a negative-AND function proving that
(A+B)' = A'.B' and we can show this using the following truth table.

Inputs Output For Each Term

A B A+B (A+B)' A' B' A'.B'

0 0 0 1 1 1 1

0 1 1 0 1 0 0

1 0 1 0 0 1 0

1 1 1 0 0 0 0

Let's take some examples in which we take some expressions and apply
DeMorgan's theorems.

Example 1: (A.B.C)'

(A.B.C)'=A'+B'+C'

Example 2: (A+B+C)'

(A+B+C)'=A'.B'.C

Example 3: ((A+BC')'+D(E+F')')'

For applying the DeMorgan's theorem on this expression, we have to follow


the following expressions:

• In complete expression, first, we find those terms on which we can apply the
DeMorgan's theorem and treat each term as a single variable.
So,

• Next, we apply DeMorgan's first theorem. So,

• Next, we use rule number 9, i.e., (A=(A')') for canceling the double bars.

• Next, we apply DeMorgan's second theorem. So,

• Again apply rule number 9 to cancel the double bar

Now, this expression has no term in which we can apply any rule or theorem.
So, this is the final expression.

Example 3: (AB'.(A + C))'+ A'B.(A + B + C')'

• Use of data types on variables


Definition of datatype: is a type of data. a better definition of a data
type is a data storage format that can contain a specific type or range of
values. It specifies the type of data that the variable can store like
integer, character, floating, double, etc.

Every Variable has a data type that tells what kind of data is being stored in a
variable. There are two types of data types in JavaScript.

• Primitive data types


• Non-primitive data types

Primitive data types: The predefined data types provided by JavaScript


language are known as primitive data types. Primitive data types are also known
as in-built data types.

Below is a list of Primitive Data Types with proper descriptions and examples:

• Number: Number data type in javascript can be used to hold decimal


values as well as values without decimals.

• String: The string data type in javascript represents a sequence of


characters that are surrounded by single or double quotes.

• Undefined: The meaning of undefined is ‘value is not assigned’.

• Boolean: The boolean data type can accept only two values i.e. true and false.

• Null: This data type can hold only one possible value that is null.

• BigInt: This data type can represent numbers greater than 253-1 which helps
to perform operations on large numbers. The number is specified by writing
‘n’ at the end of the value

• Symbol: This data type is used to create objects which will always be unique.
these objects can be created using Symbol constructor.

Non-primitive data types: The data types that are derived from primitive data
types of the JavaScript language are known as non-primitive data types. It is
also known as derived data types or reference data types.

Below is a list of Non-primitive data types.

Below is a list of Non-primitive Data Types with proper descriptions and examples:

• Object: An object in Javascript is an entity having properties


and methods. Everything is an object in javascript.

When describing objects and their purpose in JavaScript, one can look at
the distinction between properties and methods. Property is the value stored in
the hash key, while function is the method stored there. Properties define it,
while methods allow it to do things.

• Array: With the help of an array, we can store more than one
element under a single name.

Difference between Primitive vs Non-Primitive:

Primitive Non-Primitive

Primitive Data types are predefined. Non-Primitive data types are created by the
programmer

Primitive Data types will have certain Non-Primitive data types can be NULL.
values.

Size depends on the type of data Size is not fixed


structure.
Examples are numbers and strings. Examples are Array and Linked List.
It can start with a lowercase. It can start with uppercase.
• Application of datatypes

JavaScript is a dynamically typed language. It means that a variable


HYPERLINK "https://www.javascripttutorial.net/javascript-variables/"
HYPERLINK "https://www.javascripttutorial.net/javascript-variables/"
HYPERLINK "https://www.javascripttutorial.net/javascript-variables/" doesn’t
associate with a type. In other words, a variable can hold a value of different
types. For example:

let counter = 120; // counter is a


number counter = false; //
counter is now a boolean
counter = "foo"; // counter is now a stringCode language: JavaScript (javascript)

To get the current type of the value that the variable stores, you use the typeof HYPERLINK
"https://www.javascripttutorial.net/javascript-typeof/" HYPERLINK
"https://www.javascripttutorial.net/javascript-typeof/" HYPERLINK
"https://www.javascripttutorial.net/javascript-typeof/" operator:

let counter = 120;


console.log(typeof(counter));
// "number" counter = false;
console.log(typeof(counter));
// "boolean" counter = "Hi";
console.log(typeof(counter)); // "string"Code language: JavaScript (javascript)

Output:

"
n
u
m
b
e
r
"

"
b
o
o
l
e
a
n
"

"
s
t
r
i
n
g
"

The undefined type

The undefined type is a primitive type that has only one value undefined. By
default, when a variable is declared but not initialized, it is assigned the value of
undefined.

Consider the following example:

let counter;
console.log(counter); // undefined
console.log(typeof counter); // undefinedCode language: JavaScript (javascript)

In this example, the counter is a variable. Since counter hasn’t been initialized,
it is assigned the value undefined. The type of counter is also undefined.

It’s important to note that the typeof operator also returns undefined when
you call it on a variable that hasn’t been declared:

console.log(typeof undeclaredVar); // undefinedCode language: JavaScript (javascript)

The null type

The null type is the second primitive data type that also has only one value null.

For example: let obj = null;


console.log(typeof obj); // objectCode language: JavaScript (javascript)

The typeof null returns object is a known bug in JavaScript. A proposal to


fix this was proposed but rejected. The reason was the that fix would
break a lot of existing sites.

JavaScript defines that null is equal to undefined as follows:

console.log(null == undefined); // trueCode language:

JavaScript (javascript) The number type

JavaScript uses the number type to represent both integer and floating-

point numbers. The following statement declares a variable and

initializes its value with an integer: let num = 100;Code language:

JavaScript (javascript)
To represent a floating-point number, you include a decimal point followed by
at least one number. For example:

let price= 12.5;


let discount = 0.05;Code language: JavaScript (javascript)

Note that JavaScript automatically converts a floating-point number into an


integer number if the number appears to be a whole number.

The reason is that Javascript always wants to use less memory since a
floating-point value uses twice as much memory as an integer value. For
example:

let price = 200.00; // interpreted as an integer 200Code language: JavaScript (javascript)

To get the range of the number type, you use


Number.MIN_VALUE and Number.MAX_VALUE. For
example:

console.log(Number.MAX_VALUE); // 1.7976931348623157e+308
console.log(Number.MIN_VALUE); // 5e-324Code language: JavaScript
(javascript)

Also, you can use Infinity and -Infinity to represent the infinite number. For example:

console.log(Number.MAX_VALUE + Number.MAX_VALUE); // Infinity


console.log(-Number.MAX_VALUE - Number.MAX_VALUE); // -
InfinityCode language: JavaScript (javascript)
NaN

NaN stands for Not a Number. It is a special numeric value that indicates an
invalid number. For example, the division of a string by a number returns NaN:.

console.log('a'/2); // NaN;Code language: JavaScript

(javascript) The NaN has two special

characteristics:
• Any operation with NaN returns NaN.
• The NaN does not equal any value, including itself.

Here are some examples:

console.log(NaN/2); // NaN
console.log(NaN == NaN); // falseCode language: JavaScript (javascript)

The string type

In JavaScript, a string is a sequence of zero or more characters. A string


literal begins and ends with either a single quote(') or a double quote (").

A string that begins with a double quote must end with a double quote. Likewise,
a string that begins with a single quote must also end with a single quote:

let greeting = 'Hi';


let message = "Bye";Code language: JavaScript (javascript)

If you want to single quote or double quotes in a literal string, you need to use
the backslash to escape it. For example:

let message = 'I\'m also a valid string'; // use \ to escape the single quote
(')Code language: JavaScript (javascript)

JavaScript strings are immutable. This means that it cannot be modified


once created. However, you can create a new string from an existing
string. For example:

let str = 'JavaScript';

str = str + ' String';Code language: JavaScript

(javascript) In this example:


• First, declare the str variable and initialize it to a string of 'JavaScript'.

• Second, use the + operator to combine 'JavaScript' with ' String' to


make its value as 'Javascript String'.

Behind the scene, the JavaScript engine creates a new string that holds
the new string 'JavaScript String' and destroys the original strings
'JavaScript' and ' String'.
The following example attempts to change the first character of the

string JavaScript: let s = 'JavaScript';

s[0] = 'j';

console.log(s)Code language: JavaScript

(javascript) The output is:

'JavaScript'Code language: JavaScript

(javascript) But not:


'javaScript'Code language: JavaScript (javascript)

The boolean type

The boolean type has two literal values: true and false in lowercase. The
following example declares two variables that hold the boolean values.

let
inProgress
= true; let
completed
= false;

console.log(typeof completed); // booleanCode language: JavaScript

(javascript) JavaScript allows values of other types to be converted into

boolean values of true or false.

• Application of

JavaScript operators What is

an Operator?
In JavaScript, an operator is a special symbol used to perform operations
on operands (values and variables). For example, 2 + 3; // 5. Here + is an
operator that performs addition, and 2 and 3 are operands.

Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called


operands and ‘+’ is called the operator. JavaScript supports the following types
of operators.
• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators

• Conditional (or ternary)


Operators Lets have a look on
all operators one by one.
Arithmetic Operators

JavaScript supports the following arithmetic

operators − Assume variable A holds 10 and

variable B holds 20, then −


Sr.No. Operator & Description

1
+ (Addition)

Adds two operands

Ex: A + B will give 30

2
- (Subtraction)

Subtracts the second operand from the first

Ex: A - B will give -10


3
* (Multiplication)

Multiply both operands

Ex: A * B will give 200

4
/ (Division)

Divide the numerator by the denominator

Ex: B / A will give 2

5
% (Modulus)

Outputs the remainder of an integer division

Ex: B % A will give 0

6
++ (Increment)

Increases an integer value by one

Ex: A++ will give 11

7
-- (Decrement)

Decreases an integer value by one

Ex: A-- will give 9

Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" +
10 will give "a10".
Example

The following code shows how to use arithmetic operators in JavaScript.


result = a - b;
document.writ
e(result);
document.writ
e(linebreak);

document.writ
e("a / b = ");
result = a / b;
document.writ
e(result);
document.writ
e(linebreak);

document.write
("a % b = ");
result = a % b;
document.write
(result);
document.write
(linebreak);

document.write("a
+ b + c = "); result
= a + b + c;
document.write(res
ult);
document.write(lin
ebreak);

a = ++a;
document.writ
e("++a = ");
result = ++a;
document.writ
e(result);
document.writ
e(linebreak);

b = --b;
document.wr
ite("--b = ");
result = --b;
document.wr
ite(result);
document.write(linebreak);
/
/
-
-
>
<
/
s
c
r
i
p
t
>

Set the variables to different values and then try...

Output
a

4
3
a

2
3

3
.
3

3
a + b + c = 43Test
++a = 35
--b = 8
Set the variables to different values and then try...
Comparison Operators

JavaScript supports the following comparison

operators − Assume variable A holds 10 and

variable B holds 20, then –


Sr.No. Operator & Description

1
= = (Equal)

Checks if the value of two operands are equal or not, if yes, then the condition
becomes true.
Ex: (A == B) is not true.

2
!= (Not Equal)

Checks if the value of two operands are equal or not, if the values are not equal,
then the condition becomes true.
Ex: (A != B) is true.

3
> (Greater than)

Checks if the value of the left operand is greater than the value of the right
operand, if yes, then the condition becomes true.
Ex: (A > B) is not true.
4
< (Less than)

Checks if the value of the left operand is less than the value of the right operand,
if yes, then the condition becomes true.
Ex: (A < B) is true.

5
>= (Greater than or Equal to)

Checks if the value of the left operand is greater than or equal to the value of the
right operand, if yes, then the condition becomes true.
Ex: (A >= B) is not true.

6
<= (Less than or Equal to)

Checks if the value of the left operand is less than or equal to the value of the
right operand, if yes, then the condition becomes true.
Ex: (A <= B) is true.

Example

The following code shows how to use comparison operators in JavaScript.

document.writ
e(result);
document.writ
e(linebreak);

document.write("(
a < b) => "); result
= (a < b);
document.write(re
sult);
document.write(li
nebreak);
document.write("(
a > b) => "); result
= (a > b);
document.write(re
sult);
document.write(li
nebreak);

document.write("(a
!= b) => "); result
= (a != b);
document.write(res
ult);
document.write(lin
ebreak);

document.write("(a
>= b) => "); result
= (a >= b);
document.write(res
ult);
document.write(line
break);

document.write("(a
<= b) => "); result
= (a <= b);
document.write(res
ult);
document.write(line
break);
//-->
</script>
Set the variables to different values and different operators and then try...
</body>
</html>

Output
(a
==
b)
=>
false
(a <
b)
=>
true
(a >
b)
=>
false
(a !
= b)
=>
true
(a
>=
b)
=>
false
a <=
b)
=>
true
Set the variables to different values and different operators and then try...

Logical Operators

JavaScript supports the following logical

operators − Assume variable A holds 10 and

variable B holds 20, then −


Sr.No. Operator & Description

1
&& (Logical AND)

If both the operands are non-zero, then the condition becomes true.

Ex: (A && B) is true.

2
|| (Logical OR)

If any of the two operands are non-zero, then the condition becomes true.

Ex: (A || B) is true.

3
! (Logical NOT)

Reverses the logical state of its operand. If a condition is true, then the Logical
NOT operator will make it false.
Ex: ! (A && B) is false.

Example

Try the following code to learn how to implement Logical Operators in JavaScript.

<html>
<body>
<script type = "text/javascript">
<!--
var a = true;
var b = false;
var linebreak = "<br />";

document.write("(a && b) => ");


result = (a && b);
document.write(result);
document.write(linebreak);
document.write("(a || b) => ");
result = (a || b);
document.write(result);
document.write(linebreak);

document.write("!(a && b) => ");


result = (!(a && b));
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

Output
(a
&&
b) =>
false
(a ||
b) =>
true
!(a && b) => true
Set the variables to different values and different operators and then try...

Bitwise Operators

JavaScript supports the following bitwise

operators − Assume variable A holds 2 and

variable B holds 3, then −


Sr.No. Operator & Description
1
& (Bitwise AND)

It performs a Boolean AND operation on each bit of its integer arguments.

Ex: (A & B) is 2.

2
| (BitWise OR)

It performs a Boolean OR operation on each bit of its integer arguments.

Ex: (A | B) is 3.

3
^ (Bitwise XOR)

It performs a Boolean exclusive OR operation on each bit of its integer


arguments. Exclusive OR means that either operand one is true or operand two is
true, but not both.
Ex: (A ^ B) is 1.

4
~ (Bitwise Not)

It is a unary operator and operates by reversing all the bits in the operand.

Ex: (~B) is -4.

5
<< (Left Shift)

It moves all the bits in its first operand to the left by the number of places
specified in the second operand. New bits are filled with zeros. Shifting a value
left by one position is equivalent to multiplying it by 2, shifting two positions is
equivalent to multiplying by 4, and so on.

Ex: (A << 1) is 4.
6
>> (Right Shift)

Binary Right Shift Operator. The left operand’s value is moved right by the
number of bits specified by the right operand.
Ex: (A >> 1) is 1.

7
>>> (Right shift with Zero)

This operator is just like the >> operator, except that the bits shifted in on the left
are always zero.
Ex: (A >>> 1) is 1.

Example

Try the following code to implement Bitwise operator in JavaScript.

(a & b) => 2
(
a

b
)

=
>

(
a

^
b
)

=
>

(
~
b
)

=
>

-
4
(a
<
<
b)
=
>
16
(a
>
>
b)
=
>
0
Set the variables to different values and different operators and then try...

Assignment Operators
JavaScript supports the following assignment operators −

Sr.No. Operator & Description

1
= (Simple Assignment )

Assigns values from the right side operand to the left side operand

Ex: C = A + B will assign the value of A + B into C

2
+= (Add and Assignment)

It adds the right operand to the left operand and assigns the result to the left
operand.
Ex: C += A is equivalent to C = C + A

−= (Subtract and Assignment)


3

It subtracts the right operand from the left operand and assigns the result to the
left operand.
Ex: C -= A is equivalent to C = C - A

4
*= (Multiply and Assignment)

It multiplies the right operand with the left operand and assigns the result to the
left operand.
Ex: C *= A is equivalent to C = C * A
5
/= (Divide and Assignment)

It divides the left operand with the right operand and assigns the result to the left
operand.
Ex: C /= A is equivalent to C = C / A

6
%= (Modules and Assignment)

It takes modulus using two operands and assigns the result to the left operand.

Ex: C %= A is equivalent to C = C % A

Note − Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=,
|= and ^=.

Example

Try the following code to implement assignment operator in JavaScript.

Output
Value of a => (a =
b) => 10 Value of
a => (a += b) =>
20 Value of a =>
(a -= b) => 10
Value of a => (a
*= b) => 100
Value of a =>
(a /= b) => 10
Value of a => (a
%= b) => 0
Set the variables to different values and different operators and then try...

Miscellaneous Operator

We will discuss two operators here that are quite useful in JavaScript: the
conditional operator (? :) and the typeof operator.

Conditional Operator (? :)

The conditional operator first evaluates an expression for a true or false


value and then executes one of the two given statements depending upon
the result of the evaluation.

Sr.No. Operator and Description

1
? : (Conditional )

If Condition is true? Then value X : Otherwise value Y

Example

Try the following code to understand how the Conditional Operator works in JavaScript.

Output
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100
Set the variables to different values and different operators and then try...

typeof Operator

The typeof operator is a unary operator that is placed before its single operand,
which can be of any type. Its value is a string indicating the data type of the
operand.

The typeof operator evaluates to "number", "string", or "boolean" if its operand


is a number, string, or boolean value and returns true or false based on the
evaluation.
Here is a list of the return values for the typeof Operator.

Type String Returned by typeof


Number "number"

String "string"

Boolean "boolean"

Object "object"

Function "function"

Undefined "undefined"

Null "object"

Example

The following code shows how to implement typeof operator.

<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";

result = (typeof b == "string" ? "B is String" : "B is Numeric");


document.write("Result => ");
document.write(result);
document.write(linebreak);

result = (typeof a == "string" ? "A is String" : "A is Numeric");


document.write("Result => ");
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

Output
Result => B
is String
Result => A
is Numeric
• Write an algorithm
An algorithm is a procedure or step-by-step instruction for solving a problem.
They form the foundation of writing a program.

For writing any programs, the following has to be known:

• Input
• Tasks to be preformed
• Output expected

Type of algorithms used in javascript.

1. Sorting algorithms

Javascript provides a rich set of data types and operators that can be used
to implement various sorting algorithms such as bubble sort, insertion sort
and quick sort.

These algorithms are useful in many applications because they can be used
to sort data of different sizes and types.

There are different sorting

algorithms. they are:-


• Bubble sort: An uncomplicated sorting algorithm that compares nearby
components repeatedly and switches them out if they are out of order.
The Algorithm for Bubble sort is:-

• Start with an unsorted list of elements.

• Compare the first two elements in the list. If the first element is larger
than the second element, swap them.
• Move on to the next pair of elements and repeat step 2 until the end
of the list is reached.
• For each item on the list, repeat steps 2 and 3 once more. that is referred to as passes.

• Repeat steps 2-4 for the entire list. As you repeat the passes, elements
will "bubble up" to their correct position in the sorted list.
• Once a pass is completed and no swaps are made, the list is sorted, and
the algorithm can stop.
• The final sorted list is returned.

• Insertion sort: a method of sorting that creates a sorted list one individual
element at a time by placing each one in the appropriate spot.

The Algorithm for Insertion sort is:-

• Initialize an empty sorted list and an unsorted list of the elements to be sorted.

• The first member from the unsorted list should be taken and placed in
the appropriate position in the sorted list.
• Repeat step 2 for each subsequent element in the unsorted list.

• Compare the current element with the elements in the sorted list,
starting with the element immediately to the left.
• Swap the two elements if the current element is smaller than the element to its left.

• If the current element is larger than the element to its left, insert it
at its correct position in the sorted list.
• Repeat steps 4-6 for each subsequent element in the unsorted list.

• Once all elements have been processed, the sorted list will contain all
elements in the correct order.
• The sorting process is complete.

• Selection sort: a method of sorting that consistently starts the sorted


listing with the smallest detail from the unordered listing.
The Algorithm for Selection sort is:-

• Begin by setting the primary element of list as the min element.

• Repeat through the remaining items in the list, comparing each one
to the current minimum.
• Set a new minimum if an element is found to be smaller than the existing one.

• Change the current minimum to the first element of the list whenever
it reaches its conclusion.
• For the remaining unsorted portion of the listing, repeat steps 2-4, but
begin with the second item on the list (as the first element is already
sorted).
• Continue sorting the list in this manner until it is all sorted.

• Quick sort: A divide-and-conquer sorting algorithm that chooses a pivot


element and splits the list into sublists depending on whether the elements are
fewer than or more than the pivot. After that, the sublists are sorted repeatedly
until the full list is sorted.

The Algorithm for Quick sort is:-

• Choose a pivot element from the list. This is typically the first element,
but it can also be a random element or the median of the list.
• Divide the list into two sublists: one containing elements less than the
pivot and one containing elements greater than the pivot.
• Recursively sort the sublist containing elements less than the pivot
using the same process.
• Use the same procedure to recursively sort the sublist of entries larger than the pivot.

• Concatenate the sorted sublists with the pivot element in between to


form a fully sorted list.
• Return the fully sorted list.

• Merge sort: The divide-and-conquer sort algorithm divides the list into two
halves, sorts each half, and then merges the two halves in sorted order.

Merge-sort Algorithm:
• Make two sublists out of the list: one with elements below the pivot
and one with elements above the pivot.
• Produces a new sorted sublist by iteratively merging sublists until
only one sublist exists. This will be your sorted list.
• Steps to merge two sub-directories:-
• Create an empty list to hold the sorted elements.
• Compares the first element of each sublist.
• Adds the smaller element to the new list and removes it from the parent sublist.
• Repeat the steps 2 and 3 until a list is completly empty.
• Adds the remaining elements from other sublists to a new list.
• Replaces the merged sublist with the new sorted list.
• Repeat this process until all sublists are merged into one sorted list.

• Heapsort: A sorting algorithm that sorts elements using a data structure called heap.

This is the classification algorithm:

• Build max heap: Starting with the first non-leaf node, compare each
node with its child nodes and replace the nodes with the largest of its
children to satisfy the max heap property.
• Swap root with last element: Swap the root (largest element) with the
last element in the stack.
• Stack the rest of the elements. Starting from the root, each node is
compared with its children, swapping nodes with their older children
until the max heap property is satisfied.
• Repeat steps 2 and 3 with the newly stacked elements, except for the
last element in the correct position.
• Repeat this process until only one element remains in the stack. This is now sorted.

• Heapify Down: Starting from the root node, it compares elements


with its children and swaps with the larger of the two until the max
heap property is satisfied.
• Heapify Up: Start with the last element in the heap, compare it to its
parent, and swap it with the parent to satisfy the max heap property.

• Radix sort: A sorting algorithm that sorts elements based on the digits or
digits of their binary representation.

The Algorithm for Radix sort is:-

• determine how many digits are contained in the input listing's largest element.
• Initialize a variable, say digit place, to 1, which represents the current digit place.
• Create an empty list for each possible digit value from 0 to 9.

• Iterate through the input list and add each element to the appropriate list
based on the value of the current digit place.
• Concatenate all the lists together to form the new list in the order of the digit lists.
• Multiply digitPlace by 10 to move to the next digit place.

• Repeat steps 4-6 for each digit place until all digits in the largest
element have been considered.
• The final list will be sorted in ascending order by the digits of the elements.

• Return the final sorted list.

2. Searching algorithms

C also provides the tools necessary to implement a variety of searching


algorithms, such as linear search and binary search. These algorithms can quickly
find specific items in a data set, making them useful for a wide range of
applications.

There are many types of

search algorithms. They are:-


• Linear search: A basic search algorithm that examines each item in the
listing one by one until it finds the desired item.

Algorithm for Linear search:-

• Define the input for the algorithm: The input for a linear search
algorithm is a list of elements (or an array) and a target element we are
searching for.
• Initialize a variable called "index" to -1: This variable will be used to
store the index of the target element if it is found.
• Loop through the list of elements: Starting from the first element, check
each element in the list one by one.
• Compare the present element to the desired element for evaluation: Keep
the index of the current element in the index variable and exit the loop if
the modern element and the goal element are identical.
• Return the index of the target element: After the loop completes, return
the value stored in the index variable. If the target element is not found,
the value of the index will be -1

• Binary search: A search algorithm that operates by splitting the listing


into halves and searches within of those halves is more likely to include the
element.

Algorithm for Binary search:-

• Input: A sorted list of n elements and a target element x.

• Initialize variables: Set the low index to 0, the high index to n-


1, and mid to (low+high)/2.
• Start a loop: While the low index is less than or equal to the high
index, repeat the following steps.
• Compare the mid element with x: If the mid element is equal to x,
return the mid index.
• Update the low or high index: If x is greater than the mid element, set the
low index to mid + 1. Else, set the high index to mid - 1.
• Update the mid index: Mid = (low+high)/2.

• End of the loop: If the low index is greater than the high index, then x is
not in the list, and the algorithm returns a failure.
• Output: The index of x in the list or failure message.

• Depth-first search: A search algorithm that examines each branch as far


as is feasible before turning around.

The following guidelines apply to depth-first search:

• select the graph's starting vertex or node to start with.


• Add a visiting mark to the first vertex.
• Directly place the beginning vertex into a stack.
• Until the stack is empty, repeat the following actions: -
• Remove the stack's top vertex.

• Mark as visited and insert into the stack each unvisited


neighbour of the popped vertex.
• Continue this process until all vertices in the graph have been visited.

• Once all vertices have been visited, the algorithm is complete, and a
depth-first search is performed on the graph.

• Breadth-first search: A search algorithm that explores all the neighbors of a


node before moving to the next level.

The algorithm for the breadth-first search is:-

• Start with the root node or the initial state.


• Add the root node to a queue.
• Check if the queue is empty; if yes, then terminate the algorithm.
• Take the first element from the queue and mark it as visited.
• Amplify the contemporary node by adding all its unvisited neighbors to the queue.
• Until the desired node is located or the queue is empty, repeat steps 3 to 5.
• Return the path from the preliminary state to the target state if the goal node is found.

• Terminate the set of rules and report that the goal state was not identified
if the queue is empty.

• Interpolation Search: A search algorithm that uses the values of the searched
elements to estimate the position in the index.

It is important that the array is evenly distributed. Otherwise, it is

an algorithm. It works as expected.


The algorithm can be summarized as follows.

• Get the input list and key value to search.


• Initialize the lower and upper variables at the first and last indices of the list.
• If the Lower value is less than or equal to higher value, then :-
• Calculate the estimated location using the following
formula: pos = low + ((high - low) / (arr[high] -
arr[low])) * (x - arr[low]).
• Return the position if the estimated position value is a key value.

• c) If the estimated position value is less than the key value,


set it lower. Position + 1.
• d) If the value of the estimated position is greater than the
key Set value, position - 1 up.
4. If the key value is not found, return -1 to indicate that the value is not in the list.

• Jump search: A search method that iterates over the list in constant-length
steps until it finds the relevant element or determines that it is no longer
present.

The jump search algorithm is as follows:

• First, set the jump size to the square root of the number of array elements.
• Sets a variable named "current" to the first element of the array.

• Iterates over the array by jumping by jump size while incrementing a


variable called "jump".
• Move on to the following leap if the existing element is smaller
than the desired element.
• If the current element is larger than the target element, perform a linear
search between the current element and the previous jump element to
find the target element.
• If the target element is not found in the array, it returns -1 to indicate
that it is not in the array.
• If the element is found, it returns the element's index in the array.

• Graph algorithms

C's support for pointers and data structures such as arrays and linked lists
makes it suitable for implementing algorithms that manipulate graphs, such as
finding the shortest path between two nodes in a graph.

There are different types of graph algorithms.


they are:-

• Dijkstra's Algorithm: An algorithm that finds the shortest path between


two nodes in a graph by continuously updating the shortest distance from
each node.
• Algorithm A*: A method that continually updates the shortest course to
each node in a graph to determine the shortest route between them.
• Prim's Algorithm: An approach for figuring out the weighted
connected graph's smallest spanning tree.
• Kruskal's algorithm: An approach to identify the linked weighted
graph's lowest spanning tree.

• Bellman-Ford Algorithm: An algorithm that, even when the graph has


negative edge weights, displays the shortest path between a particular
supply node and every other node in the network.

• Cryptographic Algorithms

C supports low-level operations and efficient data manipulation, making it ideal


for implementing algorithms used in cryptography, such as data encryption and
decryption algorithms.

There are different types of encryption

algorithms. They are:-


• Hash Algorithms: These algorithms produce fixed-size outputs (hash)
from arbitrary- sized inputs. Examples include MD5, SHA-1 and SHA-2.
• Symmetric key algorithms: The encryption and decryption steps in
such algorithms employ the same private key. AES, DES, and Blowfish
are a few examples.
• Asymmetric key algorithms: A public key and a non-public key are
used by those methods as separate keys for encryption and decryption.
Some examples include RSA, ECC, and DSA.
• Key exchange algorithms: These algorithms allow two parties to
exchange keys over an insecure channel securely. For example, we can
mention Diffie-Hellman and Elliptic Curve Diffie-Hellman.
Characteristics/qualities of a good algorithm

• Efficiency: A good algorithm should perform its task quickly and


use minimal resources.
• Correctness: It must produce the correct and accurate output for all valid inputs.

• Clarity: The algorithm should be easy to understand and


comprehend, making it maintainable and modifiable.
• Scalability: It should handle larger data sets and problem sizes without
a significant decrease in performance.

• Reliability: The algorithm should consistently deliver correct results


under different conditions and environments.
• Optimality: Striving for the most efficient solution within the
given problem constraints.
• Robustness: Capable of handling unexpected inputs or errors
gracefully without crashing.
• Adaptability: Ideally, it can be applied to a range of related problems
with minimal adjustments.
• Simplicity: Keeping the algorithm as simple as possible
while meeting its requirements, avoiding unnecessary
complexity.

Develop an algorithm using structured English

Structured English is the use of the English language HYPERLINK


"https://en.wikipedia.org/wiki/English_language" HYPERLINK
"https://en.wikipedia.org/wiki/English_language" HYPERLINK
"https://en.wikipedia.org/wiki/English_language" with the syntax HYPERLINK
"https://en.wikipedia.org/wiki/Programming_language_syntax" HYPERLINK
"https://en.wikipedia.org/wiki/Programming_language_syntax" HYPERLINK
"https://en.wikipedia.org/wiki/Programming_language_syntax" of structured
programming HYPERLINK
"https://en.wikipedia.org/wiki/Structured_programming" HYPERLINK
"https://en.wikipedia.org/wiki/Structured_programming" HYPERLINK
"https://en.wikipedia.org/wiki/Structured_programming" to communicate the
design of a computer program to non-technical users by breaking it down into
logical steps using straightforward English words. Structured English gives aims
to get the benefits of both the programming logic and natural language: program
logic helps to attain precision, whilst natural language helps with the familiarity
of the spoken word.

Structured English

Structure English is derived from structured programming language which


gives more understandable and precise description of process. It is based on
procedural logic that uses construction and imperative sentences designed to
perform operation for action.

• It is best used when sequences and loops in a program must be


considered and the problem needs sequences of actions with
decisions.
• It does not have strict syntax rule. It expresses all logic in terms of
sequential decision structures and iterations.

For example, see the following sequence of actions −

if customer
pays
advance
then
Give 5% Discount

else
if purchase
amount
>=10,000 then
if the customer is a regular
customer then Give 5%
Discount
else
No
Discou
nt end
if
else
No
Discou
nt end
if
end if

Following are the algorithm of the sum and the average of three numbers
is given below.

Explanation:

Step 1: Start

Step 2: Read the three number suppose "a","b","c" form the user.

Step 3: Declared a variable "sum" and "Avg".

Step 4 : sum=a+b+c;

Step 5: Avg=sum/3

Step 6: Display "sum " and "Avg".

Step 7: End.

Find the Largest Number Using if-else Statements

The idea is to use the compound expression where each number is compared
with the other two to find out which one is the maximum of them.

Algorithm

• Check if A is greater than or equal to both B and C, A is the largest number.

• Check if B is greater than or equal to both A and C, B is the largest number.


• Check if C is greater than or equal to both A and B, C is the largest number.

Develop an algorithm using pseudocode

1. Definition:
Sequence, the order that commands are executed by a computer, allows us to carry out tasks
that have multiple steps.
In programming, sequence is a basic algorithm: A set of logical steps carried out in order.
Computers need instructions in the form of an algorithm in order to complete a desired task,
and this algorithm must have the correct order of steps, or sequence.

• Selection/conditional structures
A CONDITIONAL is a type of step in an algorithm where a
decision must be made. Computers follow logical instructions and
they need to know how to handle different decisions so that
programs can proceed no matter what the outcome of those
selections may be.

• IF-THEN-ELSE CONDITIONALS
One of the first things that programmers learn is how to use IF-THEN-
ELSE statements. Every programming language has some version of
these. The syntax and exact usage may be different but they all
accomplish the same thing, which is to allow for program execution
based on conditionals. The basic flow is: If some condition is true then
do this, otherwise do that.
Complex conditional statements can have more than just two choices. As
humans, the way we make decisions when we have several options to
choose from is very different than computers. We are able to select one
item out of a group of choices, however a computer program must
proceed by making binary decisions, meaning that it can only select
between two things at a time. Even the most complex conditional
statements boil down to a series of binary choices.

• SWITCH AND CASE CONDITIONALS


The switch statement is used to allow you to perform different actions based
on different conditions. In some languages this was a common structure for
conditional execution that makes it easier for a program to execute one of
several cases depending on the value of the expression at the switch.

Pseudocode is an informal way of programming description that does not require


any strict programming language syntax or underlying technology
considerations. It is used for creating an outline or a rough draft of a program.
Pseudocode summarizes a program’s flow, but excludes underlying details.

Pseudo code can be broken down into five components.

• Variables:

• Assignment:

• Input/output:

• Selection:

• Repetition:

Advantages of pseudocode –

• Pseudocode is understood by the programmers of all types.


• It enables the programmer to concentrate only on the algorithm
part of the code development.
• It cannot be compiled into an executable program.
• The main goal of a pseudo code is to explain what exactly each line
of a program should do, hence making the code construction phase
easier for the programmer.

Best practices for writing pseudocode

Some pseudocode rules include:

• Capitalize the construct keyword.


• Apply one construct per line unless pairing it with a construct like IF-THEN.
• Indent the code when using multiple constructs.
• Use plain language that describes the problem.
• Use the phrase END plus the construct keyword to show that
an element of pseudocode is complete, such as ENDFOR and
ENDWHILE.

Examples

1: Write pseudo code that reads two numbers and multiplies them together and
print out their product.

2: Write pseudo code that tells a user that the number they entered is not a 5 or a 6.

3: Write pseudo code that performs the following: Ask a user to enter a number.
If the number is between 0 and 10, write the word blue. If the number is
between 10 and 20, write the word red. if the number is between 20 and 30,
write the word green. If it is any other number, write that it is not a correct
color option.

4: Write pseudo code to print all multiples of 5 between 1 and 100


(including both 1 and 100).

5: Write pseudo code that will count all the even numbers up to a user defined

stopping point. 6: Write pseudo code that will perform the following.
• Read in 5 separate numbers.

• Calculate the average of the five numbers.

• Find the smallest (minimum) and largest (maximum) of the five entered numbers.

• Write out the results found from steps b and c with a message describing what they are.

Homework

1: Write pseudo code that reads in three numbers and writes them all in sorted order.

2: Write pseudo code that will calculate a running sum. A user will enter numbers
that will be added to the sum and when a negative number is encountered, stop
adding numbers and write out the final result.

• Design of Flowchart

Flowchart: It is a diagram of the sequence of movements or actions of


people or things involved in a complex system or activity.
It is a graphical representation of a computer program in relation to its sequence
of functions (as distinct from the data it processes).

When to Use a Flowchart

• To develop understanding of how a process is done


• To study a process for improvement
• To communicate to others how a process is done
• When better communication is needed between people involved
with the same process
• To document a process
• When planning a project

Flowchart Basic Procedure

Materials needed: Sticky notes or cards, a large piece of flipchart paper or


newsprint, and marking pens.

• Define the process to be diagrammed. Write its title at the top of the work surface.
• Discuss and decide on the boundaries of your process: Where or when
does the process start? Where or when does it end? Discuss and decide
on the level of detail to be included in the diagram.
• Brainstorm the activities that take place. Write each on a card or sticky note.
• Arrange the activities in proper sequence.
• When all activities are included and everyone agrees that the
sequence is correct, draw arrows to show the flow of the process.
• Review the flowchart with others involved in the process (workers,
supervisors, suppliers, customers) to see if they agree that the
process is drawn accurately.

Description of Elements

of Flowchart Flowchart

Symbols
Here is a chart for some of the common symbols used in drawing flowcharts.
Symbol Symbol Name Purpose

Start/Stop Used at the beginning and end of the algorithm to


show start and end of the program.

Process Indicates processes like mathematical operations.

Input/ Output Used for denoting program inputs and outputs.

Stands for decision statements in a program, where


Decision
answer is usually Yes or No.

Arrow Shows relationships between different shapes.

On-page Connector Connects two or more parts of a flowchart, which


are on the same page.

Off-page Connects two parts of a flowchart which are spread


Connector over different pages.

Guidelines for Developing Flowcharts

These are some points to keep in mind while developing a flowchart −

• Flowchart can have only one start and one stop symbol
• On-page connectors are referenced using numbers
• Off-page connectors are referenced using alphabets
• General flow of processes is top to bottom or left to right
• Arrows should not cross each other

Example Flowcharts

Here is the flowchart for going to the market to purchase a pen.

Here is a flowchart to calculate the average of two numbers.

https://www.tutorialspoint.com/programming_methodologies/programming_methodologies_f
lowchart_elements.htm

Learning outcome 2: Apply Data Structure


• Data structure concepts are clearly identified based on intended use.
• Identification of data structure concepts

Definition of Data structures: A data structure is a specialized format for


organizing, processing, retrieving and storing data.

Classification of Data Structure:


Data structure has many different uses in our daily life. There are many
different data structures that are used to solve different mathematical and
logical problems.

Linear data structure: Data structure in which data elements are arranged
sequentially or linearly, where each element is attached to its previous and next
adjacent elements, is called a linear data structure.
Examples of linear data structures are array, stack, queue, linked list, etc.
• Static data structure: Static data structure has a fixed
memory size. It is easier to access the elements in a static
data structure.
An example of this data structure is an array.
• Dynamic data structure: In the dynamic data structure,
the size is not fixed. It can be randomly updated during
the runtime which may be considered efficient
concerning the memory (space) complexity of
the code.
Examples of this data structure are queue, stack, etc.
Non-linear data structure: Data structures where data elements are not
placed sequentially or linearly are called non-linear data structures. In a non-
linear data structure, we can’t traverse all the elements in a single run only.
Examples of non-linear data structures are trees and graphs.

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 organizing, retrieving, managing, and
storing data. Here is a list of the needs for data.

• Data structure modification is easy.

• It requires less time.

• Save storage memory space.

• Data representation is easy.

• Easy access to the large database.

• List

representation

What is a List in

JavaScript?
In JavaScript, a 'List' is a synonym for an 'Array'. For beginners, think of an array
as a list, like a shopping list. This list has slots where you put the items you want
to buy. In JavaScript, these slots are called 'indices' and the items in the list are
called 'elements'.

Elements and Indices

The elements in an array can be anything: numbers, strings, boolean values,


other arrays, and even objects. In JavaScript, arrays are zero-indexed. This
means that the first slot in the array is not number 1, but number 0. Here's an
example of an array:

var fruits = ["apple", "banana", "cherry", "date"];

In this array, "apple" is at index 0, "banana" is at index 1, and so on.

Elements and Indices

The elements in an array can be anything: numbers, strings, boolean values,


other arrays, and even objects. In JavaScript, arrays are zero-indexed. This
means that the first slot in the array is not number 1, but number 0. Here's an
example of an array:

var fruits = ["apple", "banana", "cherry", "date"];

In this array, "apple" is at index 0, "banana" is at index 1, and so on.

Accessing Elements

To access an element in an array, you use its index.

For example: console.log(fruits[0]); // Outputs: apple


Modifying Elements

You can change an element in an array by accessing it with its index and
assigning a new value. For example:

fruits[1] = "blueberry";
console.log(fruits); // Outputs: ["apple", "blueberry", "cherry", "date"]

Array Length

The length of an array is the number of elements in it. You can get the
length of an array using the length property:

console.log(fruits.length); // Outputs: 4

Adding and Removing Elements

JavaScript provides several methods to add or remove elements from an array:

• push: Adds one or more elements to the end of an array, and returns the
new length of the array.

fruits.push("elderberry");
console.log(fruits); // Outputs: ["apple", "blueberry", "cherry", "date", "elderberry"]

• pop: Removes the last element from an array and returns

that element. var lastFruit = fruits.pop();


console.log(lastFruit); // Outputs: elderberry
console.log(fruits); // Outputs: ["apple", "blueberry", "cherry", "date"]

• unshift: Adds one or more elements to the beginning of an array, and


returns the new length of the array.

fruits.unshift("avocado");
console.log(fruits); // Outputs: ["avocado", "apple", "blueberry", "cherry", "date"]

• shift: Removes the first element from an array and returns

that element. var firstFruit = fruits.shift();


console.log(firstFruit); // Outputs: avocado
console.log(fruits); // Outputs: ["apple", "blueberry", "cherry", "date"]

Looping Over Arrays

You can use a for loop to iterate over the elements

in an array: for (var i = 0; i < fruits.length; i++) {


console.log(fruits[i]);
}

This will output:

a
p
p
l
e
b
l
u
e
b
e
r
r
y

c
h
e
r
r
y

d
a
t
e
In this representation, we use two types of nodes one for representing the
node with data called 'data node' and another for representing only references
called 'reference node'. We start with a 'data node' from the root node in the
tree. Then it is linked to an internal node through a 'reference node' which is
further linked to any other node directly. This process repeats for all the
nodes in the tree.
The above example tree can be represented using List representation as follows...

• List operations
List operators (JavaScript)

Lists can be processed as entities by

certain operators. The following


operators work on lists:

Operation Description

list1 + list2 Returns list1 plus list2.

list1 - list2 Returns list1 minus list2.

list1 * list2 Returns list1 times list2.

list1 / list2 Returns list1 divided bylist2.

Usage

A list means a multi-value variable such as an array.

A list operation processes the corresponding elements of two lists, or each


element of one list and a scalar value. The return value is a list. If two list
operands are not the same length, the last element of the shorter list fills out the
operation.

Examples
This example adds the corresponding elements of two arrays.

function p(stuff) {

print("<<<" + stuff + ">>>");

a = new Array(1, 2, 3);

b = new Array(0.1, 0.2, 0.3); c =


a + b;
p(c); // <<<1.1>>>,<<<2.2>>>,<<<3.3>>>

This example adds the corresponding elements of two arrays. The first array is
shorter so its last element fills out the operation.
function p(stuff) {
print("<<<" + stuff + ">>>");

a = new Array(1, 2, 3);

b = new Array(0.1, 0.2, 0.3, 0.4, 0.5);

c = a + b;

p(c); // <<<1.1>>>,<<<2.2>>>,<<<3.3>>>,<<<3.4>>>,<<<3.5>>>

This example adds a scalar value to each element of an array.

function p(stuff) {

print("<<<" + stuff + ">>>");

a = new Array(1, 2, 3); c =


a + 0.01;
p(c); // <<<1.01>>>,<<<2.01>>>,<<<3.01>>>

Data Structure

The data structure is a particular way of organizing and storing data in a


computer so that it can be accessed and modified efficiently. It is a collection
of data values, the relationships among them, and the functions or operations
that can be applied to the data.

Arrays, Linked List, Stack, Queue, etc., are some examples of Data Structures
that are universally used in almost every realm of Computer Science i.e.
Operating systems, Compiler Design, Artificial intelligence, Graphics, and a lot
more.

Important terms used in Data Structure:

• Data: Elementary value or the collection of values. Example: Name


and id of the employee are the data about the employee.
• Group Items: Data items with subordinate data items. Example: The
name of the employee can have the first name and the last name.
• Record: The collection of various data items. Example: Name,
address, and experience of the employee can be grouped together to
form the record for the employee.
• File: Collection of various records of one type of entity.
• Attribute and Entity: An entity can be defined as the class of certain
objects, containing various attributes, where each attribute represents
the particular property of that entity.
• Field: A single elementary unit of information representing the attribute of an entity.

Why we need Data Structures:

Complexed applications and an increase in the amount of data can result in below:

• Processor speed: High-speed processing is a must to handle a large


amount of data. Still, the processor may fail to deal with such a large
amount of data, because the data is increasing day by day to the billions
of files per entity.
• Data Search: An inventory can have hundreds of items in a store, which
simply means that an application needs to traverse hundreds of items
every time to search for a particular item. This results in slowing down
the search process.
• Multiple requests: Even a very large server can fail if thousands of users
are searching the data simultaneously on a web server. The data structures
are used to solve any such problems. Thus, all the items are not required
to be searched and the required data can be searched instantly if the data
is organized to form a data structure in such a way.

Data Structures Advantages:

• Efficiency: The choice of data structures decides the efficiency of a


program. Example: Using an array may not be a very good choice if we
have some data and we need to perform the search for a particular
record. Organizing the data in an array means that we will have to search
sequentially element by element. To make the search process efficient,
we can use other data structures like an ordered array, binary search tree,
or hash tables.
• Reusability: After the implementation of a particular data structure, we
can use it at any other place. Thus, the data structures are reusable.
Compiling the implementation of data structures into libraries that can be
used by different clients, serves this purpose.
• Abstraction: The ADT provides a level of abstraction. The data structure
is specified by ADT. The client program does not get into the
implementation details and uses the data structure through the interface
only.
Data Structures Types:

• Searching techniques

Searching in data structure refers to the process of finding the required


information from a collection of items stored as elements in the computer
memory. These sets of items are in different forms, such as an array, linked list,
graph, or tree. Another way to define searching in the data structures is by
locating the desired element of specific characteristics in a collection of items.

Different Searching Metods

Searching in the data structure can be done by applying searching algorithms to


check for or extract an element from any form of stored data structure.

These algorithms are classified according to the type of search operation they
perform, such as:

• Sequential search
The list or array of elements is traversed sequentially while
checking every component of the set. For example – Linear
Search.
• Interval Search
The interval search includes algorithms that are explicitly designed for
searching in sorted data structures. In terms of efficiency, these algorithms
are far better than linear search algorithms. Example- Logarithmic Search,
Binary search.

What is Linear Search?

The linear search algorithm iteratively searches all elements of the array. It has
the best execution time of one and the worst execution time of n, where n is the
total number of items in the search array.

It is the simplest search algorithm in data structure and checks each item in the
set of elements until it matches the searched element till the end of data
collection. When the given data is unsorted, a linear search algorithm is
preferred over other search algorithms.

Complexities in linear search are given below:

Space Complexity
Since linear search uses no extra space, its space complexity is O(n), where n
is the number of elements in an array.

Time Complexity

• Best-case complexity = O(1) occurs when the searched item is


present at the first element in the search array.
• Worst-case complexity = O(n) occurs when the required element is at
the tail of the array or not present at all.
• Average- case complexity = average case occurs when the item to be
searched is in somewhere middle of the Array.

Pseudocode for Linear Search Algorithm


procedure linear_search (list, value)

for each item in the list


if match item == value
return the item's location
end if
end for
end procedure
Let’s take the following array of elements:

45, 78, 15, 67, 08, 29, 39, 40, 12, 99

To find ‘29’ in an array of 10 elements given above, as we know linear search


algorithm will check each element sequentially till its pointer points to 29 in the
memory space. It takes O(6) time to find 29 in an array. To find 15, in the above
array, it takes O(3), whereas, for 39, it requires O(7) time.

What is Binary Search?

This algorithm locates specific items by comparing the middlemost items in the
data collection. When a match is found, it returns the index of the item. When
the middle item is greater than the search item, it looks for a central item of the
left sub-array. If, on the other hand, the middle item is smaller than the search
item, it explores for the middle item in the right sub-array. It keeps looking for
an item until it finds it or the size of the sub-arrays reaches zero.

Binary search needs sorted order of items of the array. It works faster than a
linear search algorithm. The binary search uses the divide and conquers
principle.

Run-time complexity = O(log n)

Complexities in binary search are given below:

• The worst-case complexity in binary search is O(n log n).


• The average case complexity in binary search is O(n log n)
• Best case complexity = O (1)

Pseudocode for Binary Search Algorithm


Procedure binary_search
A ← sorted array
n ← size of array
x ← value to be searched
Set lowerBound = 1
Set upperBound = n
while x not found
if upperBound < lowerBound
EXIT: x does not exists.
set midPoint = lowerBound + ( upperBound - lowerBound ) / 2
if A[midPoint] x
set upperBound = midPoint - 1
if A[midPoint] = x
EXIT: x found at location midPoint

en
d
w
hi
le
en
d
pr
oc
ed
ur
e
E
xa
m
pl
e,

Let’s take a sorted array of 08 elements:


09, 12, 26, 39, 45, 61, 67, 78

• To find 61 in an array of the above elements,


• The algorithm will divide an array into two arrays, 09, 12, 26, 39 and 45, 61, 67, 78
• As 61 is greater than 39, it will start searching for elements on the
right side of the array.
• It will further divide the into two such as 45, 61 and 67, 78
• As 61 is smaller than 67, it will start searching on the left of that sub-array.
• That subarray is again divided into two as 45 and 61.
• As 61 is the number matching to the search element, it will return the
index number of that element in the array.
• It will conclude that the search element 61 is located at the 6th position in an array.

Binary search reduces the time to half as the comparison count is reduced
significantly as compared to the linear search algorithm.

Space complexity refers to the amount of memory used by an algorithm or a


program during its execution.

Time complexity, on the other hand, refers to the amount of time it takes for an
algorithm or program to complete its execution.
Classification of Sorting Algorithms
Sorting is an algorithm which arranges the elements of a given list in a
particular order [ascending or descending].
Sorting algorithms are categorized on the following basis –

• By number of comparisons:
Comparison-based sorting algorithms check the elements of the list
by key comparison operation and need at least O(n log n)
comparisons for most inputs. In this method, algorithms are
classified based on the number of comparisons.
For comparison based sorting algorithms, best case behavior is O(n
log n) and worst case behavior is O(n2). For example – Quick Sort,
Bubble Sort, Insertion Sort etc.
• By Number of Swaps:

In this method, sorting algorithms are categorized by the number of


swaps (interchanging of position of two numbers, also called
inversion).
• By Memory Usage:
Some sorting algorithms are “in place” and they need O(1) or O(log
n) memory to create auxiliary locations for sorting the data
temporarily.
• By Recursion:
Sorting algorithms are either recursive (for example – quick sort) or
non- recursive (for example – selection sort, and insertion sort), and
there are some algorithms which use both (for example – merge
sort).
• By Stability:

Sorting algorithm is stable if two elements with equal values appear


in the same order in output as it was in the input. The stability of a
sorting algorithm can be checked with how it treats equal elements.
Stable algorithms preserve the relative order of equal elements,
while unstable sorting algorithms don’t. In other words, stable
sorting maintains the position of two equals elements similar to one
another. For example – Insertion Sort, Bubble Sort , and Radix Sort.

• By Adaptability:
In a few sorting algorithms, the complexity changes based on pre-sorted input
i.e. pre-sorted array of the input affects the running time. The
algorithms that take this adaptability into account are known to be
adaptive algorithms. For example – Quick sort is an adaptive
sorting algorithm because the time complexity of Quick sort
depends on the initial input sequence. If input is already sorted then
time complexity becomes O(n^2) and if input sequence is not
sorted then time complexity becomes O(n logn).
Some adaptive sorting algorithms are: Bubble Sort, Insertion Sort
and Quick Sort. On the other hand, some non-adaptive sorting
algorithms are: Selection Sort, Merge Sort, and Heap Sort.
• Internal Sorting:
Sorting algorithms that use main memory exclusively during the sort
are called internal sorting algorithms. This kind of algorithm
assumes high-speed random access to all memory. Some of the
common algorithms that use this sorting feature are: Bubble Sort,
Insertion Sort., and Quick Sort.
• External Sorting:
Sorting algorithms that use external memory, during the sorting
come under this category. They are comparatively slower than
internal sorting algorithms. For example, merge sort algorithm. It
sorts chunks that each fit in RAM, then merges the sorted chunks
together.

Sorting techniques

Sorting refers to rearrangement of a given array or list of elements according


to a comparison operator on the elements. The comparison operator is used to
decide the new order of elements in the respective data structure.
Types of Sorting Techniques
There are various sorting algorithms are used in data structures. The following
two types of sorting algorithms can be broadly classified:

• Comparison-based: We compare the elements in a comparison-


based sorting algorithm)
• Non-comparison-based: We do not compare the elements in a non-
comparison- based sorting algorithm)

In the following sections, we list some important scientific applications where


sorting algorithms are used

• When you have hundreds of datasets you want to print, you


might want to arrange them in some way.
• Sorting algorithm is used to arrange the elements of a list in a
certain order (either ascending or descending).
• Searching any element in a huge data set becomes easy. We can
use Binary search method for search if we have sorted data. So,
Sorting become important here.
• They can be used in software and in conceptual problems
to solve more advanced problems.
Some of the most common sorting algorithms are:
Below are some of the most common sorting algorithms:

• Selection sort
Selection sort is another sorting technique in which we find the minimum
element in every iteration and place it in the array beginning from the first
index. Thus, a selection sort also gets divided into a sorted and unsorted
subarray.

Working of Selection Sort algorithm:

Lets consider the following array as an example: arr[] = {64, 25, 12, 22, 11}

First pass:
For the first position in the sorted array, the whole array is traversed from
index 0 to 4 sequentially. The first position where 64 is stored presently, after
traversing whole array it is clear that 11 is the lowest value.
64 25 12 22 11

Thus, replace 64 with 11. After one iteration 11, which happens to be the least
value in the array, tends to appear in the first position of the sorted list.

11 25 12 22 64

Second Pass:
For the second position, where 25 is present, again traverse the rest of the
array in a sequential manner.

11 25 12 22 64

After traversing, we found that 12 is the second lowest value in the array and it
should appear at the second place in the array, thus swap these values.

11 12 25 22 64

Third Pass:
Now, for third place, where 25 is present again traverse the rest of the array
and find the third least value present in the array.
11 12 25 22 64

While traversing, 22 came out to be the third least value and it should appear
at the third place in the array, thus swap 22 with element present at third
position.
11 12 22 25 64

Fourth pass:
Similarly, for fourth position traverse the rest of the array and find the fourth
least element in the array
As 25 is the 4th lowest value hence, it will place at the fourth position.

11 12 22 25 64

Fifth Pass:
At last the largest value present in the array automatically get placed at the last
position in the array
The resulted array is the sorted array.

11 12 22 25 64

• Bubble sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly
swapping the adjacent elements if they are in the wrong order. This algorithm
is not suitable for large data sets as its average and worst-case time complexity
is quite high.

Working of Bubble Sort algorithm:

Lets consider the following array as an example: arr[] = {5, 1, 4, 2, 8}

First Pass:
Bubble sort starts with very first two elements, comparing them to check which
one is greater.
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps

since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8
> 5), algorithm does not swap them.
Second Pass:
Now, during second iteration it should look like this:

( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Third Pass:
Now, the array is already sorted, but our algorithm does not know if it is
completed. The algorithm needs one whole pass without any swap to know
it is sorted.
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Illustration:

Illustration of Bubble Sort

• Insertion Sort
Insertion sort is a simple sorting algorithm that works similarly to the way you
sort playing cards in your hands. The array is virtually split into a sorted and an
unsorted part. Values from the unsorted part are picked and placed at the correct
position in the sorted part.

Working of Insertion Sort algorithm:

Consider an example: arr[]: {12, 11, 13, 5, 6}


12 11 13 5 6

First Pass:
• Initially, the first two elements of the array are compared in insertion sort.

12 11 13 5 6

• Here, 12 is greater than 11 hence they are not in the ascending


order and 12 is not at its correct position. Thus, swap 11 and 12.
• So, for now 11 is stored in a sorted sub-array.

11 12 13 5 6

Second Pass:
• Now, move to the next two elements and compare them

11 12 13 5 6

• Here, 13 is greater than 12, thus both elements seem to be in


ascending order, hence, no swapping will occur. 12 also stored in a
sorted sub-array along with 11
Third Pass:
• Now, two elements are present in the sorted sub-array which are 11 and 12
• Moving forward to the next two elements which are 13 and 5

11 12 13 5 6

• Both 5 and 13 are not present at their correct place so swap them

11 12 5 13 6

• After swapping, elements 12 and 5 are not sorted, thus swap again
11 5 12 13 6

• Here, again 11 and 5 are not sorted, hence swap again

5 11 12 13 6

• here, it is at its correct position

Fourth Pass:
• Now, the elements which are present in the sorted sub-array are 5, 11 and 12
• Moving to the next two elements 13 and 6

5 11 12 13 6

• Clearly, they are not sorted, thus perform swap between both

5 11 12 6 13

• Now, 6 is smaller than 12, hence, swap again

5 11 6 12 13

• Here, also swapping makes 11 and 6 unsorted hence, swap again

5 6 11 12 13

• Finally, the array is completely sorted.


Illustrations:

• Merge Sort
The Merge Sort algorithm is a sorting algorithm that is based on the Divide
and Conquers paradigm. In this algorithm, the array is initially divided into
two equal halves and then they are combined in a sorted manner.

Let’s see how Merge Sort uses Divide and Conquer:

The merge sort algorithm is an implementation of the divide and conquers


technique. Thus, it gets completed in three steps:

• Divide: In this step, the array/list divides itself recursively into


sub-arrays until the base case is reached.

• Conquer: Here, the sub-arrays are sorted using recursion.


• Combine: This step makes use of the merge( ) function to
combine the sub- arrays into the final sorted array.

Working of Merge Sort algorithm:

To know the functioning of merge sort, let’s consider an array arr[] = {38, 27, 43, 3, 9, 82,
10}

At first, check if the left index of array is less than the right index, if yes then
calculate its mid point

Now, as we already know that merge sort first divides the whole array
iteratively into equal halves, unless the atomic values are achieved.

Here, we see that an array of 7 items is divided into two arrays of size 4 and 3 respectively.

Now, again find that is left index is less than the right index for both arrays, if
found yes, then again calculate mid points for both the arrays.
Now, further divide these two arrays into further halves, until the atomic units
of the array is reached and further division is not possible.

After dividing the array into smallest units, start merging the elements again
based on comparison of size of elements

Firstly, compare the element for each list and then combine them into another
list in a sorted manner.

After the final merging, the list looks like this:

• Quick sort
Quicksort is a sorting algorithm based on the divide and conquer approach
where an array is divided into subarrays by selecting a pivot element (element
selected from the array).

• While dividing the array, the pivot element should be positioned in


such a way that elements less than the pivot are kept on the left
side, and elements greater than the pivot is on the right side of the
pivot.
• The left and right subarrays are also divided using the same
approach. This process continues until each subarray contains a
single element.
• At this point, elements are already sorted. Finally, elements are
combined to form a sorted array.

Working of Quick Sort algorithm:


To know the functioning of Quick sort, let’s consider an array arr[] = {10, 80,
30, 90, 40, 50, 70}
• Indexes: 0 1 2 3 4 5 6
• low = 0, high = 6, pivot = arr[h] = 70
• Initialize index of smaller element, i = -1

Step1

• Traverse elements from j = low to high-1


• j = 0: Since arr[j] <= pivot, do i++ and swap(arr[i], arr[j])
• i=0
• arr[] = {10, 80, 30, 90, 40, 50, 70} // No change as i and j are same
• j = 1: Since arr[j] > pivot, do nothing

Step2

• j = 2 : Since arr[j] <= pivot, do i++ and swap(arr[i], arr[j])


• i=1

arr[] = {10, 30, 80, 90, 40, 50, 70} // We swap 80 and 30

Step3

• j = 3 : Since arr[j] > pivot, do nothing // No change in i and arr[]


• j = 4 : Since arr[j] <= pivot, do i++ and swap(arr[i], arr[j])
• i=2
• arr[] = {10, 30, 40, 90, 80, 50, 70} // 80 and 40 Swapped

Step 4

• j = 5 : Since arr[j] <= pivot, do i++ and swap arr[i] with arr[j]
• i=3

arr[] = {10, 30, 40, 50, 80, 90, 70} // 90 and 50 Swapped

Step 5
• We come out of loop because j is now equal to high-1.
• Finally we place pivot at correct position by swapping arr[i+1]
and arr[high] (or pivot)
• arr[] = {10, 30, 40, 50, 70, 90, 80} // 80 and 70 Swapped

Step 6

• Now 70 is at its correct place. All elements smaller than 70 are


before it and all elements greater than 70 are after it.
• Since quick sort is a recursive function, we call the partition
function again at left and right partitions

Step 7

• Again call function at right part and swap 80 and 90

Step 8

• Heap sort
Heap sort is a comparison-based sorting technique based on Binary Heap data
structure. It is similar to the selection sort where we first find the minimum
element and place the minimum element at the beginning. Repeat the same
process for the remaining elements.
Working of Heap Sort algorithm:
To understand heap sort more clearly, let’s take an unsorted array and try to sort
it using heap sort. Consider the array: arr[] = {4, 10, 3, 5, 1}.

Build Complete Binary Tree: Build a complete binary tree from the array.

Build complete binary tree from the array


Transform into max heap: After that, the task is to construct a tree from that
unsorted array and try to convert it into max heap.
• To transform a heap into a max-heap, the parent node should
always be greater than or equal to the child nodes
• Here, in this example, as the parent node 4 is smaller
than the child node 10, thus, swap them to build a max-
heap.

Transform it into a max heap

• Now, as seen, 4 as a parent is smaller than the child 5, thus swap


both of these again and the resulted heap and array should be like
this:

Make the tree a max heap

Perform heap sort: Remove the maximum element in each step (i.e., move it to
the end position and remove that) and then consider the remaining elements
and transform it into a max heap.
• Delete the root element (10) from the max heap. In order to delete
this node, try to swap it with the last node, i.e. (1). After removing
the root element, again heapify it to convert it into max heap.

Resulted heap and array should look like this:

Remove 10 and perform heapify

• Repeat the above steps and it will look like the following:

Remove 5 and perform heapify

Now remove the root (i.e. 3) again and perform heapify.

Remove 4 and perform heapify


• Now when the root is removed once again it is sorted. and the
sorted array will be like arr[] = {1, 3, 4, 5, 10}.

The sorted array

• Counting sort
Counting sort is a sorting technique based on keys between a specific range. It
works by counting the number of objects having distinct key values (kind of
hashing). Then do some arithmetic to calculate the position of each object in the
output sequence.
Working of Counting Sort algorithm:
Consider the array: arr[] = {1, 4, 1, 2, 7, 5, 2}.

• Input data: {1, 4, 1, 2, 7, 5, 2}


Take a count array to store the count of each unique object.

• Now, store the count of each unique element in the count array
• If any element repeats itself, simply increase its count.

• Here, the count of each unique element in the count array is as shown below:
• Index: 0 1 2 3 4 5 6 7 8 9

Count: 0 2 2 0 1 1 0 1 0 0

• Modify the count array such that each element at each index
stores the sum of previous counts.

• Index: 0 1 2 3 4 5 6 7 8 9
• Count: 0 2 4 4 5 6 6 7 7 7
• The modified count array indicates the position of each object
in the output sequence.
• Find the index of each element of the original array in the count
array. This gives the cumulative count.
• Rotate the array clockwise for one time.

• Index: 0123456789
• Count: 0024456677

• Output each object from the input sequence followed by increasing


its count by 1.
• Process the input data: 1, 4, 1, 2, 7, 5, 2. Position of 1 is 0.

• Put data 1 at index 0 in output. Increase count by 1 to place next


data 1 at an index 1 greater than this index.

• After placing each element at its correct position, decrease its count by one.
Application of linear data structures and their operations

Characteristics of Linear Data Structure:


• Sequential Organization: In linear data structures, data elements
are arranged sequentially, one after the other. Each element has a
unique predecessor (except for the first element) and a unique
successor (except for the last element)
• Order Preservation: The order in which elements are added to the
data structure is preserved. This means that the first element added
will be the first one to be accessed or removed, and the last element
added will be the last one to be accessed or removed.
• Fixed or Dynamic Size: Linear data structures can have either fixed
or dynamic sizes. Arrays typically have a fixed size when they are
created, while other structures like linked lists, stacks, and queues
can dynamically grow or shrink as elements are added or removed.
• Efficient Access: Accessing elements within a linear data structure
is typically efficient. For example, arrays offer constant-time access
to elements using their index.
Linear data structures are commonly used for organising and
manipulating data in a sequential fashion. Some of the most common
linear data structures include:
• Arrays: A collection of elements stored in contiguous memory locations.
• Linked Lists: A collection of nodes, each containing an element and
a reference to the next node.
• Stacks: A collection of elements with Last-In-First-Out (LIFO) order.
• Queues: A collection of elements with First-In-First-Out (FIFO) order.
• Array
An array is a collection of items of same data type stored at contiguous memory locations.

Array

Characteristics of Array Data Structure:


• Homogeneous Elements: All elements within an array must be of
the same data type.
• Contiguous Memory Allocation: In most programming languages,
elements in an array are stored in contiguous (adjacent) memory
locations.
• Zero-Based Indexing: In many programming languages, arrays use
zero-based indexing, which means that the first element is accessed
with an index of 0, the second with an index of 1, and so on.
• Random Access: Arrays provide constant-time (O(1)) access to
elements. This means that regardless of the size of the array, it takes
the same amount of time to access any element based on its index.
Types of arrays:
• One-Dimensional Array: This is the simplest form of an array,
which consists of a single row of elements, all of the same data type.
Elements in a 1D array are accessed using a single index.

One-Dimensional Array

• Two-Dimensional Array: A two-dimensional array, often


referred to as a matrix or 2D array, is an array of arrays. It
consists of rows and columns, forming a grid-like structure.
Elements in a 2D array are accessed using two indices, one for
the row and one for the column.

Two-Dimensional Array:

• Multi-Dimensional Array: Arrays can have more than two


dimensions, leading to multi-dimensional arrays. These are used
when data needs to be organized in a multi-dimensional grid.

Multi-Dimensional Array

Types of Array operations:


• Accessing Elements: Accessing a specific element in an array by
its index is a constant-time operation. It has a time complexity of
O(1).
• Insertion: Appending an element to the end of an array is usually
a constant- time operation, O(1) but insertion at the beginning or
any specific index takes O(n) time because it requires shifting all
of the elements.
• Deletion: Same as insertion, deleting the last element is a
constant-time operation, O(1) but deletion of element at the
beginning or any specific index takes O(n) time because it
requires shifting all of the elements.
• Searching: Linear Search takes O(n) time which is useful for
unsorted data and Binary Search takes O(logn) time which is useful
for sorted data.
• Linked List
A Linked List is a linear data structure which looks like a chain of nodes,
where each node contains a data field and a reference(link) to the next node in
the list. Unlike Arrays, Linked List elements are not stored at a contiguous
location.
Common Features of Linked List:
• Node: Each element in a linked list is represented by a node, which
contains two components:
• Data: The actual data or value associated with the element.

• Next Pointer(or Link): A reference or pointer to the next


node in the linked list.
• Head: The first node in a linked list is called the “head.” It serves as
the starting point for traversing the list.
• Tail: The last node in a linked list is called the “tail.”
Types of Linked Lists:
• Singly Linked List: In this type of linked list, every node stores
the address or reference of the next node in the list and the last
node has the next address or reference as NULL. For example: 1-
>2->3->4->NULL

Singly Linked List

• Doubly Linked Lists: In a doubly linked list, each node has two
pointers: one pointing to the next node and one pointing to the
previous node. This bidirectional structure allows for efficient
traversal in both directions.

Doubly Linked Lists

• Circular Linked Lists: A circular linked list is a type of linked list


in which the first and the last nodes are also connected to each other
to form a circle, there is no NULL at the end.

Circular Linked Lists

Types of Linked List operations:


• Accessing Elements: Accessing a specific element in a linked list
takes O(n) time since nodes are stored in non conitgous locations
so random access if not possible.
• Searching: Searching of a node in linked list takes O(n) time as
whole list needs to travesed in worst case.
• Insertion: Insertion takes O(1) time if we are at the position
where we have to insert an element.
• Deletion: Deletion takes O(1) time if we know the position of the
element to be deleted.
• Stack Data Structure

A stack is a linear data structure that follows the Last-In-First-Out (LIFO)


principle, meaning that the last element added to the stack is the first one to be
removed.

Stack Data structure

Types of Stacks:
• Fixed Size Stack: As the name suggests, a fixed size stack has a
fixed size and cannot grow or shrink dynamically. If the stack is full
and an attempt is made to add an element to it, an overflow error
occurs. If the stack is empty and an attempt is made to remove an
element from it, an underflow error occurs.
• Dynamic Size Stack: A dynamic size stack can grow or shrink
dynamically. When the stack is full, it automatically increases its
size to accommodate the new element, and when the stack is
empty, it decreases its size. This type of stack is implemented
using a linked list, as it allows for easy resizing of the stack.
Stack Operations:
• push(): When this operation is performed, an element is inserted into the stack.
• pop(): When this operation is performed, an element is removed
from the top of the stack and is returned.
• top(): This operation will return the last inserted element that
is at the top without removing it.
• size(): This operation will return the size of the stack i.e. the
total number of elements present in the stack.
• isEmpty(): This operation indicates whether the stack is empty or not.
• Queue Data Structure
A queue is a linear data structure that follows the First-In-First-Out (FIFO)
principle. In a queue, the first element added is the first one to be removed.

Queue Data Structure

Types of Queue:
• Input Restricted Queue: This is a simple queue. In this type of
queue, the input can be taken from only one end but deletion can be
done from any of the ends.
• Output Restricted Queue: This is also a simple queue. In this
type of queue, the input can be taken from both ends but deletion
can be done from only one end.
•Circular Queue: This is a special type of queue where the last
position is connected back to the first position. Here also the
operations are performed in FIFO order. To know more refer this.
• Double-Ended Queue (Dequeue): In a double-ended queue the
insertion and deletion operations, both can be performed from both
ends. To know more refer this.
• Priority Queue: A priority queue is a special queue where the
elements are accessed based on the priority assigned to them.
To know more refer this.
Queue Operations:
• Enqueue(): Adds (or stores) an element to the end of the queue..
• Dequeue(): Removal of elements from the queue.
• Peek() or front(): Acquires the data element available at the front
node of the queue without deleting it.
• rear(): This operation returns the element at the rear end without removing it.
• isFull(): Validates if the queue is full.
• isNull(): Checks if the queue is empty.
Advantages of Linear Data Structures
• Efficient data access: Elements can be easily accessed by their
position in the sequence.
• Dynamic sizing: Linear data structures can dynamically adjust
their size as elements are added or removed.
• Ease of implementation: Linear data structures can be easily
implemented using arrays or linked lists.
• Versatility: Linear data structures can be used in various
applications, such as searching, sorting, and manipulation of data.

• Simple algorithms: Many algorithms used in linear data


structures are simple and straightforward.
Disadvantages of Linear Data Structures
• Limited data access: Accessing elements not stored at the end or
the beginning of the sequence can be time-consuming.
• Memory overhead: Maintaining the links between elements in
linked lists and pointers in stacks and queues can consume
additional memory.
• Complex algorithms: Some algorithms used in linear data
structures, such as searching and sorting, can be complex and
time-consuming.
•Inefficient use of memory: Linear data structures can result in
inefficient use of memory if there are gaps in the memory allocation.
• Unsuitable for certain operations: Linear data structures may
not be suitable for operations that require constant random access
to elements, such as searching for an element in a large dataset.
Most Common Operations Performed in Linear Data Structures

Next, we'll look at the most popular data structure operations. Data structure
operations refer to the methods that allow you to manipulate data within a
data structure. These are the most popular data structure operations:

• Traversal

A traversal operation is used to visit every data structure node in a particular


order. This is a technique that can be used to print, search, display, and read
data stored in a structure.

• Insertion

Insertion operations add data elements to a database structure. This can be


operated at any point in the data structure, including its beginning, middle, and
end.
• Deletion

Data elements are removed from a data structure by deletion operations. These
operations are usually performed on nodes that no longer need them.

• Merge

Two data structures can be combined into one using merge operations. This is
used when two data structures need to be combined into one.

• Copy

To create a duplicate data structure, copy operations can be used. You can do
this by copying every element from the original structure to the new one.

• Search Operation

Search operations can be used to locate a particular data element within a data
structure. These operations often use a compare function in order to determine
if two elements are equal.

• Sort Operation

Sort operations are used for arranging data elements in a data structure in a
particular order. You can use a variety of sorting algorithms to accomplish
this, including bubble sort, insertion sort, and merge sort.

Non-linear data structure

• A non-linear data structure is another important type in which data


elements are not arranged sequentially; mainly, data elements are
arranged in random order without forming a linear structure.
• Data elements are present at the multilevel, for example, tree.

• In trees, the data elements are arranged in the hierarchical form, whereas
in graphs, the data elements are arranged in random order, using the edges
and vertex.
• Multiple runs are required to traverse through all the elements
completely. Traversing in a single run is impossible to traverse the whole
data structure.
• Each element can have multiple paths to reach another element.
• The data structure where data items are not organized sequentially is
called a non-linear data structure. In other words, data elements of the
non-linear data structure could be connected to more than one element to
reflect a special relationship among them.

Let us discuss some of its types:

Trees and Graphs are the types of non-linear data structures.

Tree:

• The tree is a non-linear data structure that is comprised of various nodes.


The nodes in the tree data structure are arranged in hierarchical order.

• It consists of a root node corresponding to its various child nodes, present


at the next level. The tree grows on a level basis, and root nodes have
limited child nodes depending on the order of the tree.
• For example, in the binary tree, the order of the root node is 2, which
means it can have at most 2 children per node, not more than it.
• The non-linear data structure cannot be implemented directly, and it is
implemented using the linear data structure like an array and linked list.
• The tree itself is a very broad data structure and is divided into various
categories like Binary tree, Binary search tree, AVL trees, Heap, max
Heap, min-heap, etc.
• All the types of trees mentioned above differ based on their properties.

Graph

• A graph is a non-linear data structure with a finite number of vertices and


edges, and these edges are used to connect the vertices.
• The graph itself is categorized based on some properties; if we talk about
a complete graph, it consists of the vertex set, and each vertex is
connected to the other vertexes having an edge between them.
• The vertices store the data elements, while the edges represent the
relationship between the vertices.
• A graph is very important in various fields; the network system is
represented using the graph theory and its principles in computer
networks.
• Even in Maps, we consider every location a vertex, and the path derived
between two locations is considered edges.
• The graph representation's main motive is to find the minimum distance
between two vertexes via a minimum edge weight.

Properties of Non-linear data structures

• It is used to store the data elements combined whenever they are not
present in the contiguous memory locations.
• It is an efficient way of organizing and properly holding the data.

• It reduces the wastage of memory space by providing sufficient memory


to every data element.
• Unlike in an array, we have to define the size of the array, and subsequent
memory space is allocated to that array; if we don't want to store the
elements till the range of the array, then the remaining memory gets
wasted.
• So to overcome this factor, we will use the non-linear data structure and
have multiple options to traverse from one node to another.
• Data is stored randomly in memory.
• It is comparatively difficult to implement.
• Multiple levels are involved.
• Memory utilization is effective.

What is Tree Data structure?

Trees: Unlike Arrays, Stack, Linked Lists, and queues, which are linear data
structures, trees are hierarchical.

• A tree data structure is a collection of objects or entities known as nodes


linked together to represent or simulate hierarchy.
• This data is not arranged in a sequential contiguous location like as we
have observed in an array, the homogeneous data elements are placed at
the contiguous memory location so that the retrieval of data elements is
simpler.
• A tree data structure is non-linear because it does not store sequentially.
It is a hierarchical structure as elements in a Tree are arranged in multiple
levels.

• The topmost node in the Tree data structure is known as a root node.
Each node contains some data, and data can be of any type. The node
contains the employee's name in the tree structure, so the data type would
be a string.
• Each node contains some data and the link or reference of other nodes
that can be called children.

Graphs

• One node is connected with another node with an edge in a graph. The
graph is a non- linear data structure consisting of nodes and edges and is
represented by G ( V, E ), where V stands for the set of vertices and E
stands for the set of edges. The graphs are divided into various categories:
directed, undirected, weighted and unweighted, etc.
• This data is not arranged in sequential contiguous locations as observed in
the array. The homogeneous data elements are placed at the contiguous
memory location to retrieve data elements is simpler.
• It does not have any concept of root node or child node, unlike trees.
Also, it does not have any particular order of arranging the data elements
like in trees, and we have a particular hierarchical order in which the data
elements are arranged.

• Every tree is called a graph, and in other words, we call it a spanning


tree, which has the n-1 edges, where n stands for the total number of
vertices in a graph.

Difference Between Linear and Non-linear Data Structures


Parameter Linear Data Structure Non-Linear Data Structure

Arrangement of In a linear data structure, the data In a non-linear data structure, the
Data Element elements connect to each other data elements connect to each other
sequentially. A user can transverse each hierarchically. Thus, they are present
element through a single run. at various levels.

Complexity of The linear data structures are The non-linear data structures are
Implementation comparatively easier to implement. comparatively difficult to implement
and understand as compared to the
linear data structures.

Levels A user can find all of the data elements One can find all the data elements at
at a single level in a linear data structure. multiple levels in a non-linear data
structure.

Traversal You can traverse a linear data structure It is not easy to traverse the non-
in a single run. linear data structures. The users need
multiple runs to traverse them
completely.

Utilization of It is not very memory-friendly. It means The data structure is memory-


Memory that the linear data structures can’t friendly. It means that it uses
utilize memory very efficiently. memory very efficiently.

Complexity of The time complexity of this data Non-linear data structure’s time
Time structure is directly proportional to its complexity often remains the same
size. It means that the time complexity with an increase in its input size.
increases with increasing input size.
Applications Linear data structures work well mainly Non-linear data structures work
in the development of application mainly well in image processing and
software. Artificial Intelligence.

You might also like