Data Structures Notes_012649
Data Structures Notes_012649
Competency: Apply Data Structure and Algorithm Fundamentals Using Java Script
ETP NYARUREMA
Competency: Apply Data Structure and Algorithm Fundamentals Using Java Script
1. Apply 1.1 Number systems are correctly converted according to the base
Algorithm conversion methods
Fundamenta
l 1.2 Logic gates and expressions are well described based on boolean algebra
s
1.3 Data types are effectively used according to their intended use
2.1 Data structure concepts are clearly identified based on intended use.
2. Apply Data
2.2 Linear Data Structures are properly applied based on their operational
complexity
2|Page
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 outcomes: At the end of the module the learner will be able to:
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.
Base – 8
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.
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.
5|Page
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
6|Page
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.
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
7|Page
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.
There are two main methods for converting binary number systems into decimal number
systems. These methods are:
1. Positional Notation
8|Page
2. 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
1 0 1
1 x 22 + 0 x 21 + 1 x 20
4+0+1
(5)10
1 0 1.1 0 1
(4 + 0 + 1) . (0.5 + 0 + 0.125)
(5.625)10
9|Page
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
=1
=1x2+0=2
=2x2+1=5
The formula to convert binary number system into decimal can be represented by,
Where,
For Example :
(1000)2 = 1 x 23 + 0 x 22 + 0 x 21 + 0 x 20
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
To convert a decimal number to an octal number, there are several direct and indirect
methods. They are as given below:
o Decimal to Octal Conversion Using by Direct Method: As the name suggests decimal
numbers are directly converted to octal numbers.
o 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.
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.
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.
12 | P a g e
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.
Let’s see how to convert decimal numbers to binary to octal conversion. By repeatedly
dividing a number by two and recording the result, decimal values can be transformed into
binary.
The remainders are to be read from bottom to top to obtain the binary equivalent.
4310 2
13 | P a g e
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.
0 000
1 001
2 010
3 011
4 100
5 101
6 110
7 111
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.
= (1010111100)
= (1 2 7 4)
= (1274)
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:
15 | P a g e
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 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 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:
To convert Decimal to Octal including decimal points, we first convert it to hexadecimal and
then convert it to octal.
Once we get the hexadecimal number we convert it to octal using the steps we discussed
above.
4330/8 541 2
541/8 67 5
67/8 8 3
8/8 1 0
1/8 0 1
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.
4321/8 540 1
540/8 67 4
67/8 8 3
8/8 1 0
1/8 0 1
— 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
19 | P a g e
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 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.
Solution:
To convert decimal to hex, i.e. 960 base 10 to a hexadecimal number, follow the steps given
below:
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
20 | P a g e
Let’s discuss the octal to binary conversion steps for the indirect method.
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.
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.
548=4×80+5×81
548=4×1+5×8
548=4+40
21 | P a g e
548 10
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 2
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
22 | P a g e
octal to binary by choosing the binary equivalent of every digit of the octal number from the
below-mentioned chart.
The following table includes the octal numbers 0 to 7 and their equivalent three-digit binary
representation to aid octal to binary conversion.
0 000
1 001
2 010
3 011
4 100
5 101
6 110
7 111
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.
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.
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
24 | P a g e
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 decimal:
348=(3×81)+(4×80)
348=24+4
348 10
5 5
6 6
7 7
10 8
11 9
12 A
13 B
14 C
15 D
16 E
17 F
20 10
Problem : 1
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 2
0010 = 2
1000 = 8
26 | P a g e
Problem : 2
Solution:
(56)8
= (101)(110)
=(101110) 2
(101110)2
= (10)(1110)
= (2)(14)
= (2E)16
Problem: 3
Solution:
= 3×81+6×80+1×8-1+2×8-2+5×8-3
= (30.16601563)10(30.16601563)10
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
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.
28 | P a g e
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.
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.
29 | P a g e
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."
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.
30 | P a g e
A B Y
0 0 0
0 1 1
1 0 1
1 1 0
In the XNOR gate, the output is in state 1 when both inputs are the same, that is, both 0 or
both 1.
A B Y
0 0 1
0 1 0
31 | P a g e
1 0 0
1 1 1
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.
Circuits
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.
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
32 | P a g e
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.
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
33 | P a g e
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:
1) 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,
34 | P a g e
3) Next, we use rule number 9, i.e., (A=(A')') for canceling the double bars.
Now, this expression has no term in which we can apply any rule or theorem. So, this is the
final expression.
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: 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:
1. Number: Number data type in javascript can be used to hold decimal values as well as
values without decimals.
36 | P a g e
2. String: The string data type in javascript represents a sequence of characters that are
surrounded by single or double quotes.
4. Boolean: The boolean data type can accept only two values i.e. true and false.
5. Null: This data type can hold only one possible value that is null.
6. 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
7. 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 with proper descriptions and examples:
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.
2. Array: With the help of an array, we can store more than one element under a
single name.
Primitive Non-Primitive
Examples are numbers and strings. Examples are Array and Linked List.
JavaScript is a dynamically typed language. It means that a variable doesn’t associate with a
type. In other words, a variable can hold a value of different types. For example:
To get the current type of the value that the variable stores, you use the typeof operator:
Output:
"number"
"boolean"
"string"
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.
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:
The null type is the second primitive data type that also has only one value null. For example:
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 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:
To represent a floating-point number, you include a decimal point followed by at least one
number. For example:
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:
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:
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(NaN/2); // NaN
console.log(NaN == NaN); // falseCode language: JavaScript (javascript)
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:
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:
In this example:
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';
41 | P a g e
s[0] = 'j';
console.log(s)Code language: JavaScript (javascript)
But not:
The boolean type has two literal values: true and false in lowercase. The following example
declares two variables that hold the boolean values.
JavaScript allows values of other types to be converted into boolean values of true or false.
What is an Operator?
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
42 | P a g e
Arithmetic Operators
1 + (Addition)
2 - (Subtraction)
3 * (Multiplication)
4 / (Division)
5 % (Modulus)
6 ++ (Increment)
7 -- (Decrement)
Note - Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give
"a10".
Example
<html>
<body>
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
44 | P a g e
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);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);
a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);
b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
//-->
</script>
</body>
</html>
Output
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
++a = 35
--b = 8
Set the variables to different values and then try...
Comparison Operators
1 = = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition
becomes 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.
Checks if the value of the left operand is greater than the value of the right
operand, if yes, then the condition becomes true.
Checks if the value of the left operand is less than the value of the right operand,
if yes, then the condition becomes true.
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.
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.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
document.write("(a == b) => ");
result = (a == b);
47 | P a g e
document.write(result);
document.write(linebreak);
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
If both the operands are non-zero, then the condition becomes 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.
Example
Try the following code to learn how to implement Logical Operators in JavaScript.
49 | P a g e
<html>
<body>
<script type = "text/javascript">
<!--
var a = true;
var b = false;
var linebreak = "<br />";
Bitwise Operators
50 | P a g e
Ex: (A & B) is 2.
2 | (BitWise OR)
Ex: (A | B) is 3.
3 ^ (Bitwise XOR)
Ex: (A ^ B) is 1.
4 ~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the operand.
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.
51 | P a g e
Ex: (A << 1) is 4.
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.
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
<html>
<body>
<script type = "text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";
Assignment Operators
53 | P a g e
1 = (Simple Assignment )
Assigns values from the right side operand to the left side operand
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
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
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
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
54 | P a g e
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
<html>
<body>
<script type = "text/javascript">
<!--
var a = 33;
var b = 10;
var linebreak = "<br />";
Miscellaneous Operator
We will discuss two operators here that are quite useful in JavaScript: the conditional
operator (? :) and the typeof operator.
56 | P a g e
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.
1 ? : (Conditional )
Example
Try the following code to understand how the Conditional Operator works in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
</html>
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.
Number "number"
String "string"
Boolean "boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";
• Input
• Tasks to be preformed
• Output expected
59 | P a g e
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.
they are:-
(i) Bubble sort: An uncomplicated sorting algorithm that compares nearby components
repeatedly and switches them out if they are out of order.
(ii) 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.
1. Initialize an empty sorted list and an unsorted list of the elements to be sorted.
2. The first member from the unsorted list should be taken and placed in the appropriate
position in the sorted list.
3. Repeat step 2 for each subsequent element in the unsorted list.
4. Compare the current element with the elements in the sorted list, starting with the
element immediately to the left.
5. Swap the two elements if the current element is smaller than the element to its left.
6. If the current element is larger than the element to its left, insert it at its correct
position in the sorted list.
7. Repeat steps 4-6 for each subsequent element in the unsorted list.
8. Once all elements have been processed, the sorted list will contain all elements in the
correct order.
9. The sorting process is complete.
(iii) Selection sort: a method of sorting that consistently starts the sorted listing with the
smallest detail from the unordered listing.
(iv) 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.
61 | P a g e
1. 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.
2. Divide the list into two sublists: one containing elements less than the pivot and one
containing elements greater than the pivot.
3. Recursively sort the sublist containing elements less than the pivot using the same
process.
4. Use the same procedure to recursively sort the sublist of entries larger than the pivot.
5. Concatenate the sorted sublists with the pivot element in between to form a fully
sorted list.
6. Return the fully sorted list.
(v) 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:
1. Make two sublists out of the list: one with elements below the pivot and one with
elements above the pivot.
2. Produces a new sorted sublist by iteratively merging sublists until only one sublist
exists. This will be your sorted list.
3. Steps to merge two sub-directories:-
4. Create an empty list to hold the sorted elements.
5. Compares the first element of each sublist.
6. Adds the smaller element to the new list and removes it from the parent sublist.
7. Repeat the steps 2 and 3 until a list is completly empty.
8. Adds the remaining elements from other sublists to a new list.
9. Replaces the merged sublist with the new sorted list.
10. Repeat this process until all sublists are merged into one sorted list.
(vi) Heapsort: A sorting algorithm that sorts elements using a data structure called heap.
62 | P a g e
1. 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.
2. Swap root with last element: Swap the root (largest element) with the last element in
the stack.
3. 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.
4. Repeat steps 2 and 3 with the newly stacked elements, except for the last element in
the correct position.
5. Repeat this process until only one element remains in the stack. This is now sorted.
6. 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.
7. 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.
(vii) Radix sort: A sorting algorithm that sorts elements based on the digits or digits of their
binary representation.
1. determine how many digits are contained in the input listing's largest element.
2. Initialize a variable, say digit place, to 1, which represents the current digit place.
3. Create an empty list for each possible digit value from 0 to 9.
4. Iterate through the input list and add each element to the appropriate list based on the
value of the current digit place.
5. Concatenate all the lists together to form the new list in the order of the digit lists.
6. Multiply digitPlace by 10 to move to the next digit place.
7. Repeat steps 4-6 for each digit place until all digits in the largest element have been
considered.
8. The final list will be sorted in ascending order by the digits of the elements.
63 | P a g e
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.
They are:-
(i) Linear search: A basic search algorithm that examines each item in the listing one by one
until it finds the desired item.
1. 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.
2. Initialize a variable called "index" to -1: This variable will be used to store the index
of the target element if it is found.
3. Loop through the list of elements: Starting from the first element, check each element
in the list one by one.
4. 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.
5. 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
(ii) 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.
2. Initialize variables: Set the low index to 0, the high index to n-1, and mid to
(low+high)/2.
3. Start a loop: While the low index is less than or equal to the high index, repeat the
following steps.
4. Compare the mid element with x: If the mid element is equal to x, return the mid
index.
5. 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.
6. Update the mid index: Mid = (low+high)/2.
7. 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.
8. Output: The index of x in the list or failure message.
(iii) Depth-first search: A search algorithm that examines each branch as far as is feasible
before turning around.
(iv) Breadth-first search: A search algorithm that explores all the neighbors of a node before
moving to the next level.
(v) Interpolation Search: A search algorithm that uses the values of the searched elements to
estimate the position in the index.
It works as expected.
(vi) 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.
66 | P a g e
1. First, set the jump size to the square root of the number of array elements.
2. Sets a variable named "current" to the first element of the array.
3. Iterates over the array by jumping by jump size while incrementing a variable called
"jump".
4. Move on to the following leap if the existing element is smaller than the desired
element.
5. 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.
6. If the target element is not found in the array, it returns -1 to indicate that it is not in
the array.
7. If the element is found, it returns the element's index in the array.
3. 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.
they are:-
1. 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.
2. Algorithm A*: A method that continually updates the shortest course to each node in
a graph to determine the shortest route between them.
3. Prim's Algorithm: An approach for figuring out the weighted connected graph's
smallest spanning tree.
4. Kruskal's algorithm: An approach to identify the linked weighted graph's lowest
spanning tree.
67 | P a g e
5. 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.
4. 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.
They are:-
1. Hash Algorithms: These algorithms produce fixed-size outputs (hash) from arbitrary-
sized inputs. Examples include MD5, SHA-1 and SHA-2.
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.
3. 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.
4. 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.
• 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.
68 | P a g e
• 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.
Structured English is the use of the English language with the syntax of 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.
else
if purchase amount >=10,000
then
if the customer is a regular customer
then Give 5% Discount
else No Discount
end if
else No Discount
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 4 : sum=a+b+c;
Step 5: Avg=sum/3
Step 7: End.
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
2. 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.
71 | P a g e
a. 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.
72 | P a g e
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.
73 | P a g e
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.
• Variables:
• Assignment:
• Input/output:
• Selection:
• Repetition:
Advantages of pseudocode –
Examples
74 | P a g e
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.
c) Find the smallest (minimum) and largest (maximum) of the five entered numbers.
d) 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
Materials needed: Sticky notes or cards, a large piece of flipchart paper or newsprint, and
marking pens.
1. Define the process to be diagrammed. Write its title at the top of the work surface.
2. 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.
3. Brainstorm the activities that take place. Write each on a card or sticky note.
4. Arrange the activities in proper sequence.
5. When all activities are included and everyone agrees that the sequence is correct,
draw arrows to show the flow of the process.
6. Review the flowchart with others involved in the process (workers, supervisors,
suppliers, customers) to see if they agree that the process is drawn accurately.
Flowchart Symbols
Here is a chart for some of the common symbols used in drawing flowcharts.
• 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
77 | P a g e
https://www.tutorialspoint.com/programming_methodologies/programming_methodologies_f
lowchart_elements.htm
78 | P a g e
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
79 | P a g e
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.
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.
• List representation
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'.
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:
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:
Accessing Elements
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
81 | P a g e
• 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.
• 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.
You can use a for loop to iterate over the elements in an array:
apple
blueberry
cherry
date
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)
Operation Description
Usage
83 | P a g e
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) {
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) {
c = a + b;
p(c); // <<<1.1>>>,<<<2.2>>>,<<<3.3>>>,<<<3.4>>>,<<<3.5>>>
function p(stuff) {
}
84 | P a g e
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.
• 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.
Complexed applications and an increase in the amount of data can result in below:
85 | P a g e
• 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.
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:
87 | P a g e
• 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.
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.
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.
end procedure
Let’s take the following array of elements:
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.
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.
Binary search reduces the time to half as the comparison count is reduced significantly as
compared to the linear search algorithm.
90 | P a g e
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].
1. 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.
2. 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).
3. 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.
4. 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).
5. 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.
91 | P a g e
6. 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.
7. 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.
8. 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
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:
93 | P a g e
1. 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.
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.
94 | P a g e
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
2. 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.
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
95 | P a g e
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:
96 | P a g e
3. 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.
12 11 13 5 6
First Pass:
• Initially, the first two elements of the array are compared in insertion sort.
97 | P a g e
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
5 11 12 13 6
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
5 11 6 12 13
5 6 11 12 13
4. 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.
The merge sort algorithm is an implementation of the divide and conquers technique. Thus,
it gets completed in three steps:
1. Divide: In this step, the array/list divides itself recursively into sub-arrays until
the base case is reached.
100 | P a g e
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.
101 | P a g e
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
102 | P a g e
Firstly, compare the element for each list and then combine them into another list in a
sorted manner.
5. 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).
103 | P a g e
1. 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.
2. The left and right subarrays are also divided using the same approach. This
process continues until each subarray contains a single element.
3. At this point, elements are already sorted. Finally, elements are combined to
form a sorted array.
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
Step2
Step3
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
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
Step 8
6. 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.
Build Complete Binary Tree: Build a 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:
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:
• Repeat the above steps and it will look like the following:
• Now when the root is removed once again it is sorted. and the sorted array will
be like arr[] = {1, 3, 4, 5, 10}.
7. 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.
• 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.
113 | P a g e
• 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.
• 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.
115 | P a g e
• After placing each element at its correct position, decrease its count by one.
Application of linear data structures and their operations
Array
One-Dimensional Array
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.
118 | P a g e
Multi-Dimensional Array
• 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.
• 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.
120 | P a g e
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.
4. 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.
122 | P a g e
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.
123 | P a g e
• 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:
1. 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.
2. 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.
3. Deletion
Data elements are removed from a data structure by deletion operations. These operations
are usually performed on nodes that no longer need them.
124 | P a g e
4. 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.
5. 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.
6. 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.
7. 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.
o 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.
o Data elements are present at the multilevel, for example, tree.
o 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.
o Multiple runs are required to traverse through all the elements completely. Traversing
in a single run is impossible to traverse the whole data structure.
o 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.
Tree:
o 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.
o 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.
o 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.
o 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.
o All the types of trees mentioned above differ based on their properties.
Graph
o 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.
o 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.
o The vertices store the data elements, while the edges represent the relationship between
the vertices.
o A graph is very important in various fields; the network system is represented using
126 | P a g e
the
graph theory and its principles in computer networks.
127 | P a g e
o Even in Maps, we consider every location a vertex, and the path derived between two
locations is considered edges.
o The graph representation's main motive is to find the minimum distance between two
vertexes via a minimum edge weight.
o It is used to store the data elements combined whenever they are not present in the
contiguous memory locations.
o So to overcome this factor, we will use the non-linear data structure and have multiple
options to traverse from one node to another.
Trees: Unlike Arrays, Stack, Linked Lists, and queues, which are linear data structures, trees
are hierarchical.
o 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.
o A tree data structure is non-linear because it does not store sequentially. It is a
128 | P a g e
o 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.
o Each node contains some data and the link or reference of other nodes that can be
called
children.
Graphs
o 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.
o 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.
o 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.
130 | P a g e
o 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.
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.
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.