Data Structures Notes_063611
Data Structures Notes_063611
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
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
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. 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:
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
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
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
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
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
(4 + 0 + 1) . (0.5 + 0 + 0.125)
(5.625)10
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
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
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:
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.
Conversion of Integral
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
= (1010111100)
= (1 2 7 4)
= (1274)
This is a simple procedure that involves dividing the number to be transformed by two.
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:
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
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.
hexadecimal. Solution:
To convert decimal to hex, i.e. 960 base 10 to a hexadecimal number, follow the
steps given below:
Let’s discuss the octal to binary conversion steps for the indirect method.
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.
decimal
548=4×80+5×81
548=4×1+5×8
548=4+40
548=4410
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
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.
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
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.
Example: Convert 7658 to binary.
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
348=24+4
348=2810
5 5
6 6
7 7
10 8
11 9
12 A
13 B
14 C
15 D
16 E
17 F
20 10
Hexadecimal Problem : 1
What is the hexadecimal equivalent of (50)8
Solution:
5 = 101
1 =000
(50)8=(101000)2
Problem : 2
Covert the octal number (56)8 to a hexadecimal number.
Solution:
number (56)8
= (101)(110)
=(101110)2
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
= (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.
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
In an OR gate, the output of an OR gate attains state 1 if one or more inputs attain state 1.
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."
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
is
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
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
De-Morgan's Second Theorem
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')')'
• 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 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.
Below is a list of Primitive Data Types with proper descriptions and examples:
• 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 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.
• Array: With the help of an array, we can store more than one
element under a single name.
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.
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:
Output:
"
n
u
m
b
e
r
"
"
b
o
o
l
e
a
n
"
"
s
t
r
i
n
g
"
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.
JavaScript uses the number type to represent both integer and floating-
JavaScript (javascript)
To represent a floating-point number, you include a decimal point followed by
at least one number. For example:
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:
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:.
characteristics:
• Any operation with NaN returns NaN.
• The NaN does not equal any value, including itself.
console.log(NaN/2); // NaN
console.log(NaN == NaN); // falseCode language: JavaScript (javascript)
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)
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
s[0] = 'j';
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;
• Application of
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.
1
+ (Addition)
2
- (Subtraction)
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
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
>
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
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
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
1
&& (Logical AND)
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.
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 />";
Output
(a
&&
b) =>
false
(a ||
b) =>
true
!(a && b) => true
Set the variables to different values and different operators and then try...
Bitwise Operators
Ex: (A & B) is 2.
2
| (BitWise OR)
Ex: (A | B) is 3.
3
^ (Bitwise XOR)
4
~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the operand.
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
(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 −
1
= (Simple Assignment )
Assigns values from the right side operand to the left side operand
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
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
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 (? :)
1
? : (Conditional )
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.
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 />";
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.
• Input
• Tasks to be preformed
• Output expected
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.
• 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.
• 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.
• 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.
• 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.
• 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.
• 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.
• Radix sort: A sorting algorithm that sorts elements based on the digits or
digits of their binary representation.
• 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.
2. Searching algorithms
• 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
• 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.
• Once all vertices have been visited, the algorithm is complete, and a
depth-first search is performed on the graph.
• 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.
• 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.
• 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.
• 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.
• Cryptographic Algorithms
Structured English
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 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
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.
• Variables:
• Assignment:
• Input/output:
• Selection:
• Repetition:
Advantages of pseudocode –
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.
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.
• 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
• 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
• 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
https://www.tutorialspoint.com/programming_methodologies/programming_methodologies_f
lowchart_elements.htm
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.
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
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'.
Accessing 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
• 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"]
fruits.unshift("avocado");
console.log(fruits); // Outputs: ["avocado", "apple", "blueberry", "cherry", "date"]
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)
Operation Description
Usage
Examples
This example adds the corresponding elements of two arrays.
function p(stuff) {
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 + ">>>");
c = a + b;
p(c); // <<<1.1>>>,<<<2.2>>>,<<<3.3>>>,<<<3.4>>>,<<<3.5>>>
function p(stuff) {
Data Structure
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.
Complexed applications and an increase in the amount of data can result in below:
• Searching techniques
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.
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
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.
en
d
w
hi
le
en
d
pr
oc
ed
ur
e
E
xa
m
pl
e,
Binary search reduces the time to half as the comparison count is reduced
significantly as compared to the linear search algorithm.
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:
• 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
• 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.
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.
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:
• 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.
First Pass:
• Initially, the first two elements of the array are compared in insertion sort.
12 11 13 5 6
11 12 13 5 6
Second Pass:
• Now, move to the next two elements and compare them
11 12 13 5 6
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
• 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.
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.
• 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).
Step1
Step2
arr[] = {10, 30, 80, 90, 40, 50, 70} // We swap 80 and 30
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
• 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
Step 7
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.
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.
•
• Repeat the above steps and it will look like the following:
• 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}.
• 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
• 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
• 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.
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.
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.
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
• Insertion
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.
• 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.
Tree:
Graph
• 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.
Trees: Unlike Arrays, Stack, Linked Lists, and queues, which are linear data
structures, trees are hierarchical.
• 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.
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.