Linked List Concepts and Operations
Linked List Concepts and Operations
Strictly for internal circulation (within KIIT) and reference only. Not for outside circulation without permission
3 Linked List 8
Singly Linked Lists and Chains, Representing
Chains in C, Polynomials, Sparse Matrix,
Doubly Linked Lists, Circular & Header
Linked Lists
Linked List is the linear data structure which are connected together via links and is a
sequence of nodes which contains items and connection to another node. It is the
second most used data structure after array.
Important Concepts:
Linked list can be visualized as a chain of nodes, where every node points to the next
node.
Advantages
They are a dynamic in nature which allocates memory when required.
Insertion and deletion operations can be easily implemented.
Stacks and queues can be easily executed.
Linked List reduces the access time.
Disadvantages
The memory is wasted as pointers require extra memory for storage.
No element can be accessed randomly; it has to access each node sequentially.
Reverse traversing is difficult in linked list.
Applications
Used to implement stacks, queues, graphs, etc
Maintaining directory of names
Performing arithmetic operations on long integers.
Previous and next page in web browser
In memory the linked list is stored in scattered locations. The memory for each node is
allocated dynamically i.e. as and when required. So the Linked List can increase as per
the user wish and the size is not fixed, it can vary.
Suppose first node of linked list is allocated with an address 1008. Its graphical
representation looks like :
Suppose next node is allocated with an address 10 and the list becomes
Address Comments Next
Declaration of struct that should be used to create a list where each node
holds info.
struct node
{
int info;
struct node *next;
};
The next step is to declare a pointer to serve as the list head, i.e.
struct node *head;
Once node data structure is declared and have created a NULL head pointer,
an empty linked list is created.
The next step is to implement operations with the list.
1 22 9
2 74 4
Boy CR 2 3 77 8
4 82 3
Girl CR 7 5
6 51 1
7 10 6
8 11 0
9 27 0
School of Computer Engineering
Class Work
10
Suppose the personnel file of a small company contains the following data of its
employees : Name, Employee No, Sex, Salary. Design a linked list using arrays.
Solution
So four parallel arrays say Name,
Name EmpNo Sex Salary LINK
EmpNo, Sex, Salary are required
to store the data. Additionally,
parallel array LINK is required
for the next pointer field of the
list and the variable HEAD is to
point to the 1st record in the list.
0 can be used to represent the
null pointer.
Head
School of Computer Engineering
Class Work
11
Suppose the personnel file of a small company contains the following data of its
employees : Name, Employee No, Sex, Salary. Design a linked list using structure.
Solution
struct personnel
{
8080
char *name;
8080 A 1 M 10 7080
Single Linked List− Item navigation is forward only. Also called as one-way list
Double Linked List − Items can be navigated forward and backward way
Circular Linked List − Last item contains link of the first element as next and first
element has link to last element as prev. Circular, singly linked list
Chains – A chain is a linked list in which each node represents one element
Two-Way Lists – Double and Circular Linked List
School of Computer Engineering
Double Linked List
13
Doubly Linked List is a variation of Linked list in which navigation is possible in both
ways i.e. either forward and backward.
Important Concepts:
Node − Each node of a linked list store the data
Next − Each node of a linked list contain a link to next link
Prev − Each node of a linked list contain a link to previous link
Linked List − A Linked List contains the connection link to the first Link called First
and to the last link called Last. First is also called as Head and Last is also called as
Tail.
Traversing linked list means visiting each and every node of the singly linked list. Following steps are
involved while traversing the singly linked list –
1. Firstly move to the first node
2. Fetch the data from the node and if required, perform the operations such as arithmetic operation
or any operation depending on data type.
3. After performing operation, advance pointer to next node and perform all above steps on visited
node.
Pseudocode: Class Work
void traverse() Design search algorithm for SLL (Single
{ Linked List)
struct node *temp = head; //Move to First Node
do
{
printf(“%d”, temp->data);
temp = temp->next; //Move Pointer to Next Node
}while(temp!=NULL);
}
School of Computer Engineering
Deletion
21
Pseudocode for Delete Last Node from Singly Linked List: Class Work
struct node *temp = head, t = NULL;
Design an algorithm to delete a node at a
if(head->next==NULL)
specified position.
{
free(head); Design a recursive algorithm to count
head=NULL; number of nodes in SLL.
}
else
{
for(;temp->next != NULL; temp=temp->next, t = temp);
free(t->next);
t->next=NULL;
}
Singly Linked List Double Linked List Singly Linked List as Circular
Header linked list is a linked list which always contains a special node
called the Header Node, at the beginning of the list. It does not contain
actual data item included in the list but usually contains some useful
information about the entire linked list. It has two types:
1. Grounded Header Link List− Last Node Contains the NULL Pointer
2. Circular Header Link List − Last Node Points Back to the Header
Node.
Note: Start/Head always points to Header Node.
Class Work
Write creation and display method of
Circular Header Link List
Examples –
Polynomial with single variable P(X) = 4X3 + 6X2+7X+9 (4,6,7 are coefficient & 3,2
are exponent)
Polynomial with 2 variables P(X, Y) = X3 - 2XY +1 (2 is coefficient & 3 is exponent)
Definition–
Polynomial with single variable P(X) =
Node of a polynomial:
Coefficient Exponent Next
In each node the exponent field will store the corresponding exponent and the
coefficient field will store the corresponding coefficient. Link field points to the next item
in the polynomial.
Points to keep in mind
1. The sign of each coefficient and exponent is stored within the coefficient and the
exponent itself
2. The storage allocation for each term in the polynomial must be done in descending
order of their exponent
Class Work
Design non-array based data structure to represent lower triangular, upper
triangular and tri-diagonal matrix.
Header Linked List: For example, consider the sparse matrix struct node
{
int row;
Node Structure int column;
int value;
struct node *next;
} *start;
The linked list can be represented using linked list as shown below
start 5 6 5
Header Node
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
_in_c.htm
Strictly for internal circulation (within KIIT) and reference only. Not for outside circulation without permission
Prerequisites
2 Arrays 5
Arrays, Abstract Data Type, Dynamically Allocated Arrays, Polynomials, Two-dimensional Array, Address Calculation,
Matrix Addition and Multiplication, Sparse Matrix, Upper & Lower Triangular Matrix, Tridiagonal Matrix
3 Linked List 8
Singly Linked Lists and Chains, Representing Chains in C, Polynomials, Sparse Matrix, Doubly Linked Lists, Circular &
Header Linked lists
4.1 Stacks 4
Stacks, Stacks using Dynamic Arrays and Linked List, Evaluation of Expressions
Mid Semester
4.2 Queues 4
Queues, Queue using Dynamic Arrays and Linked List, Circular Queues using Dynamic Arrays and Linked List, Evaluation
of Expressions, Priority Queue, Dequeue
5 Trees 12
Introduction, Binary Trees, Binary Tree Traversals, Threaded Binary Trees, Binary Search Trees, AVL Trees, m-way Search
Trees, B-Trees, Introduction to B+-Trees, Tree Operation, Forests
Insertion Sort, Quick Sort, Merge Sort, Heap Sort, Bubble Sort, Selection Sort, Radix Sort
8 Searching 3
Linear Search, Binary Search, Hashing – Hash Function, Collision Resolution Techniques
End Semester
Textbook
Data Structures using C by Aaron M. Tenenbaum, Yedidyah Langsam, Moshe J. Augenstein
Reference Books
Data Structures, Schaum’s OutLines, Seymour Lipschutz, TATA McGRAW HILL
Fundamentals of Data Structures in C, 2nd edition, Horowitz, Sahani, Anderson-Freed, Universities Press.
Data Structures A Pseudocode Approach with C, 2nd Edition, Richard F. Gilberg, Behrouz A. Forouzan, CENGAGE
Learning, India Edition
Data Structures and Algorithm Analysis in C, Mark Allen Weiss, Pearson Education, 2nd Edition.
Data Structures and Algorithms (Addison-Wesley Series in Computer Science and Information Pr) by Alfred V. Aho,
Jeffrey D. Ullman, John E. Hopcroft.
Understand the concepts of data structure, data type and abstract data type (ADT)
Understand and apply various data structures such as arrays, stacks, queues, trees
and graphs to solve various computing problems
Effectively choose the data structure that efficiently models the information in a
problem.
Grading:
Mini-Project = 10 marks
?
School of Computer Engineering
Definition - ADT
9
Stack ADT: A Stack contains elements of same type arranged in sequential order.
All operations takes place at a single end that is top of the stack and following
operations can be performed:
push() – Insert an element at one end of the stack called top.
pop() – Remove and return the element at the top of the stack, if it is not
empty.
peek() – Return the element at the top of the stack without removing it, if
the stack is not empty.
It is basically a group of data elements that are put together under one name and
defines a particular way of storing and organizing data in a computer so that it
can be used efficiently.
For example, we have cricket player's name "Virat" & age 28. "Virat" is of string
data type and 28 is of integer data type. This data can be organized as a record
like Player record. Now players record can be collected and store in a file or
database as a data structure. For example: "Dhoni" 30, "Gambhir" 31, "Sehwag"
33.
Characteristics Description
Linear The data items are assessed in a linear sequence, but it is not compulsory
to store all elements sequentially. Example: Array
Non-Linear The data items are stored/accessed in a non-linear order. Example: Tree,
Graph
Homogeneous All the elements are of same type. Example: Array
Heterogeneous The elements are variety or dissimilar type of data Example: Structures
Static Are those whose sizes and structures associated memory locations are
fixed, at compile time. Example: Array
Dynamic Are those which expands or shrinks depending upon the program need
and its execution. Also, their associated memory locations changes.
Example: Linked List created using pointers
What we are doing is, for a given problem (preparing an omelette), we are
providing a step-by step procedure for solving it.
ADT + Data
Structure + Algorithm
Need?
Arrays allow to define type of variables that can hold several data items of the same kind. Similarly
structure is another user defined data type available in C that allows to combine data items of
different kinds.
Structures are used to represent a record. Suppose you want to keep track of your books in a
library. You might want to track the following attributes about each book −
Title
Author
Subject
Book ID
Unions are quite similar to the structures in C. Union is also a derived type as
structure. Union can be defined in same manner as structures just the keyword
used in defining union in union where keyword used in defining structure was
struct.
You can define a union with many members, but only one member can contain a
value at any given time. Unions provide an efficient way of using the same
memory location for multiple-purpose.
Defining the Union: Data Union Access Union Elements
union [union tag] union Data /* Declare data of type Data */
{ { union Data data;
int i;
member definition;
float f; data.i =10;
member definition;
char str[20]; data.f = 34.72;
...
member definition; } data; [Link] =“C Programming”
} [one or more union variables];
Structure Union
In structure each member get separate space in In union, the total memory space allocated is
memory. Take below example. equal to the member with largest size. All other
members share the same memory space. This is
struct student the biggest difference between structure and
{ union.
int rollno;
char gender; union student
float marks; {
} s1; int rollno;
char gender;
The total memory required to store a structure float marks;
variable is equal to the sum of size of all the }s1;
members. In above case 7 bytes (2+1+4) will
be required to store structure variable s1. In above example variable marks is of float type
and have largest size (4 bytes). So the total
memory required to store union variable s1 is 4
bytes.
School of Computer Engineering
Difference b/w Structure & Union continue…
19
Pictorial Representation
Structure Union
Structure Union
We can access any member in any sequence. We can access only that variable whose value is
recently stored.
[Link] = 20;
[Link] = 90.0; [Link] = 20;
printf(“%d”,[Link]); [Link] = 90.0;
printf(“%d”,[Link]);
The exact size of array is unknown until the compile time i.e. time when a compiler compiles code
written in a programming language into a executable form. The size of array you have declared
initially can be sometimes insufficient and sometimes more than required.
What?
The process of allocating memory during program execution is called dynamic memory allocation. It
also allows a program to obtain more memory space, while running or to release space when no
space is required.
Sr # Function Description
1 void *calloc(int num, int size) Allocates an array of num elements each of which size
in bytes will be size.
2 void free(void *address) Releases a block of memory block specified by address.
3 void *malloc(int num) Allocates an array of num bytes and leave them
uninitialized.
4 void *realloc(void *address, Re-allocates memory extending it up to new size.
int newsize)
#include <stdio.h>
#include <stdlib.h>
C Program illustrating the usage of realloc
int main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = malloc( 20 * sizeof(char) );
if( mem_allocation == NULL )
{
printf("Couldn't able to allocate requested memory\n"); return;
}
else
{
strcpy( mem_allocation,“dynamic memory allocation for realloc function");
}
printf("Dynamically allocated memory content : %s\n", mem_allocation );
mem_allocation=realloc(mem_allocation,100*sizeof(char));
if( mem_allocation == NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation,"space is extended upto 100 characters");
}
printf("Resized memory : %s\n", mem_allocation );
free(mem_allocation);
return 0;
}
Sr # malloc calloc
1 It allocates only single block of It allocates multiple blocks of
requested memory requested memory
2 doesn‟t initializes the allocated initializes the allocated memory to
memory. It contains garbage values. zero
3 int *ptr; int *ptr;
ptr = malloc( 20 * sizeof(int)); Ptr = calloc( 20, 20 * sizeof(int));
For the above, 20*2 bytes of For the above, 20 blocks of memory
memory only allocated in one block. will be created and each contains
20*2 bytes of memory.
Total = 40 bytes
Total = 800 bytes
1. Input. There are zero or more quantities that are externally supplied.
2. Output. At least one quantity is produced.
3. Definiteness. Each instruction is clear and unambiguous.
4. Finiteness. If we trace out the instructions of an algorithm, then for all cases, the algorithm
terminates after a finite number of steps.
5. Effectiveness. Every instruction must be basic enough to be carried out, in principle, by a
person using only pencil and paper. It is not enough that each operation be definite as in (3); it
also must be feasible.
Difference between an algorithm & program – program does not have to satisfy the 4th condition.
Describing Algorithm
1. Natural Language – e.g. English, Chinese - Instructions must be definite and effectiveness.
2. Graphics representation – e.g. Flowchart - work well only if the algorithm is small and simple.
3. Pseudo Language -
• Readable
• Instructions must be definite and effectiveness
4. Combining English and C
Start
Input
M1 to M5
Stop
School of Computer Engineering
Pseudo Language
29
The Pseudo language is neither an algorithm nor a program. It is an abstract form of a program. It consists of
English like statements which perform the specific operations. It employs programming-like statements to
depict the algorithm and no standard format (language independent) is followed. The statements are carried out
in a order & followings are the commonly used statements.
e.g.
e.g. IF (amount < 100) THEN
IF (amount < 100) THEN interestRate .06
interestRate .06 ELSE
ENDIF interest Rate .10
ENDIF
e.g. e.g.
count 0 count 0
REPEAT WHILE (count < 10)
ADD 1 to count ADD 1 to count
OUTPUT: count OUTPUT: count
UNTIL (count < 10) ENDWHILE
OUTPUT: “The End” OUTPUT: “The End”
Write only one statement per line Each statement in pseudo code should express just one action for the computer. If the task list is properly
drawn, then in most cases each task will correspond to one line of pseudo code.
Task List Pseudo code
Read name, hours worked, rate of pay INPUT: name, hoursWorked, payRate
gross = hours worked * rate of pay gross hoursWorked * payRate
Write name, hours worked, gross OUTPUT: name, hoursWorked, gross
Capitalize initial keyword In the example above note the words: INPUT and OUTPUT. These are just a few of the keywords to use,
others include: IF, ELSE, REPEAT, WHILE, UNTIL, ENDIF
Indent to show hierarchy Each design structure uses a particular indentation pattern.
Sequence - Keep statements in sequence all starting in the same column
Selection - Indent statements that fall inside selection structure, but not the keywords that form the
selection
Loop - Indent statements that fall inside the loop but not keywords that form the loop
INPUT: name, grossPay, taxes
IF (taxes > 0)
net grossPay – taxes
ELSE
net grossPay
ENDIF
OUTPUT: name, net
Guidelines Explanation
Watch the IF/ELSE/ENDIF as constructed above, the ENDIF is in line with the IF. The same applies for
WHILE/ENDWHILE etc…
Keep statements language Resist the urge to write in whatever language you are most comfortable with, in the long run you will save
independent time. Remember you are describing a logic plan to develop a program, you are not programming!
1. Problem - Design the pseudo code to add two numbers and display the average.
INPUT: x, y
sum x + y
average sum / 2
OUTPUT: ‘Average is:’ average
2. Problem - Design the pseudo code to calculate & display the area of a circle
INPUT: radius
area 3.14 * radius * radius
OUTPUT: ‘Area of the circle is ‘ area
2. Problem - Design the pseudo code to calculate & display the largest among 2 numbers
INPUT: num1, num2
max num1
IF (num2 > num 1) THEN
max num2
ENDIF
OUTPUT: ‘Largest among 2 numbers is’ max
Theorem
Function sort(a, n) correctly sorts a set of n>= 1 integers. The result
remains in a[0], ..., a[n-1] such that a[0]<= a[1]<=...<=a[n-1].
Proof
For i= q, following the execution of lines, we have a[q]<= a[r], q< r< =n-1.
For i> q, observing, a[0], ..., a[q] are unchanged.
Hence, increasing i, for i= n-2, we have a[0]<= a[1]<= ...<=a[n-1]
int func2(int n)
{
return func1(n);
}
#include<stdio.h>
void Fibonacci(int); //continuation of program
int main() void Fibonacci(int n)
{ {
int k,n; static long int first=0,second=1,sum;
long int i=0,j=1,f;
if(n>0) Base Criteria
printf("Enter the range of the Fibonacci series: "); {
scanf("%d",&n); sum = first + second;
first = second;
printf("Fibonacci Series: "); second = sum;
printf("%d %d ",0,1); printf("%ld ",sum);
Fibonacci(n); Fibonacci(n-1); Progressive Criteria
return 0; }
} }
Hence, many solution’s algorithms can be derived for a given problem. Next step
is to analyze those proposed solution algorithms and implement the best
suitable.
A priori analysis
School of Computer Engineering
Algorithm Complexity
43
Suppose X is an algorithm and n is the size of input data, the time and
space used by the Algorithm X are the two main factors which decide the
efficiency of X.
Space complexity of an algorithm represents the amount of memory space required by the
algorithm in its life cycle. Space required by an algorithm is equal to the sum of the following two
components −
A fixed part that is a space required to store certain data and variables, that are independent of
the size of the problem. For example simple variables & constant used, program size etc.
A variable part is a space required by variables, whose size depends on the size of the problem.
For example dynamic memory allocation, recursion stack space etc.
Space complexity SC(P) of any algorithm P is SC(P) = FP + VP (I) where FP is the fixed part and
VP(I) is the variable part of the algorithm which depends on instance characteristic I. Following is a
simple example that tries to explain the concept −
Algorithm: SUM(A, B) 3 variables and data type of each variable is int, So VP(3)
Step 1 - START = 3*2 = 6 bytes (No. of characteristic i.e. I = 3)
Step 2 - C ← A + B + 10 1 constant (i.e. 10) and it is int, so FP = 1*2 = 2 bytes
Step 3 - Stop So - SC(SUM) = FP + VP (3) = 2 + 6 = 8 bytes
Example 1 Example 2
int sum(int a[], int n)
int square(int a) {
{ int sum = 0, i;
return a*a; for(i = 0; i < n; i++) { sum = sum + a[i];}
} return sum;
In above piece of code, it requires 2 bytes of }
In above piece of code it requires -
memory to store variable 'a' and another 2
• 2*n bytes of memory to store array variable ‘a[]’
bytes of memory is used for return value. • 2 bytes of memory for integer parameter 'n‘
• 4 bytes of memory for local integer variables 'sum'
That means, totally it requires 4 bytes of and 'i' (2 bytes each)
memory to complete its execution. And this • 2 bytes of memory for return value.
4 bytes of memory is fixed for any input
value of 'a'. This space complexity is said to That means, totally it requires '2n+8' bytes of memory to
complete its execution. Here, the amount of memory depends
be Constant Space Complexity.
on the input value of 'n'. This space complexity is said to be
Linear Space Complexity.
If any algorithm requires a fixed amount of
space for all input values then that space If the amount of space required by an algorithm is increased
complexity is said to be Constant Space with the increase of input value, then that space complexity is
Complexity said to be Linear Space Complexity
For example, addition of two n-bit integers takes n steps. Consequently, the total
computational time is T(n) = c*n, where c is the time taken for addition of two bits.
Here, we observe that T(n) grows linearly as input size increases.
Asymptotic analysis
Asymptotic analysis of an algorithm, refers to defining the mathematical
foundation/framing of its run-time performance.
Asymptotic analysis are input bound i.e., if there's no input to the algorithm it is
concluded to work in a constant time. Other than the "input" all other factors are
considered constant.
School of Computer Engineering
Time Complexity cont… Asymptotic analysis
47
For example,
- Running time of one operation is computed as f(n)
- May be for another operation it is computed as g(n2)
Ω Notation – “Omega” - The Ω(n) is the formal way to express the lower
bound of an algorithm's running time. It measures the best case time
complexity or best amount of time an algorithm can possibly take to complete.
θ Notation – “Theta” - The θ(n) is the formal way to express both the lower
bound and upper bound of an algorithm's running time.
Sr # Notation Name
1 O(1) Constant
2 O(log(n)) Logarithmic
3 O(log(n)c) Poly-logarithmic
4 O(n) Linear
5 O(n2) Quadratic
6 O(nc) Polynomial
7 O(cn) Exponential
Note: c is constant
Time complexity of nested loops is equal to the number of times the innermost
statement is executed that is nothing but the multiplication of outer loop complexity
into inner loop complexity.
Sr # Program Segment Time Complexity Explanation
1 for (int i = 1; i <=m; i += c) O(m+n) First for outer i loop O(m), second for
{ If m=n, then inner i loop O(n) times, so total
// some O(1) expressions O(2n)=O(n) O(m+n) times
}
for (int i = 1; i <=n; i += c)
{
// some O(1) expressions
}
2 for (int i = 1; i <=n; i *= 2) O(n) First for outer i log n times, second inner i it
{ is n times. Now total=log n + n = O(n) as n
// some O(1) expressions is asymptotically larger than log n.
}
for (int i = 1; i <=n; i ++)
{
// some O(1) expressions
}
3 int i, j, k,l; O(n log n) Nested for-ij loop is executed n log
for (i = 1; i <=n; i ++) n times. k loop log n times, l loop
{ n times. So total= n log n + log n + n =
for (j = 1; j <=n; j=j*2) {p=i+j;} O(n log n) as n log n > n > log n
}
Detailed Lessons
Functions, Structures and Unions, Pointers, Dynamic Memory Allocation, Algorithm
Specification, Space and Time Complexity
Find the time and space complexity of the following code segment
int GCD(int x, int y)
{
if y == 0 then
return x
else if x >= y AND y > 0
return GCD (y, x % y)
else
return 0;
}
Find the time and space complexity of the following code segment
void matrixAddition(int a[][], int b[][], int c[][], int n)
{
int i, j;
for (i = 0; i < n; ++i)
{
for (j = 0; j < n; ++j)
{
c[i][j] = a[i][j] + b[i][j];
}
}
}
Strictly for internal circulation (within KIIT) and reference only. Not for outside circulation without permission
2 Arrays 5
Arrays, Abstract Data Type, Dynamically Allocated
Arrays, Polynomials, Two-dimensional Array,
Address Calculation, Matrix Addition and
Multiplication, Sparse Matrix, Upper & Lower
Triangular Matrix, Tridiagonal Matrix
Arrays
Array is a container which can hold fix number of items and these items should be of
same type. Following are important terms to understand the concepts of Array. Arrays
are of one-dimensional or multi-dimensional (i.e. 2 or more than 2)
Element − Each item stored in an array.
Index − Each location of an element in an array has a numerical index which is used
to identify the element.
One-Dimensional array is also called as linear array and stores the data in a single row or column.
Array of an element of an array say “A[i]” is calculated using the following formula:
Address of A [i] = BA + w * ( i – LB )
Where,
BA = Base Address
w = Storage Size of one element stored in the array (in byte)
i = Subscript of element whose address is to be found
LB = Lower limit / Lower Bound of subscript, if not specified assume 0 (zero)
Example
Problem: Given the base address of an array B[1300…..1900] as 1020 and size of each
element is 2 bytes in the memory. Find the address of B[1700].
Solution:
The given values are: B = 1020, LB = 1300, W = 2, i = 1700
Address of A [i] = BA + w * ( i – LB )
= 1020 + 2 * (1700 – 1300)
= 1020 + 2 * 400
= 1020 + 800 = 1820
Note : C supports row major order and Fortran supports column major order
School of Computer Engineering
Row major & Column order Address Calculation
7
Row-Major Order: The address of a location in Row Major System is calculated as:
Address of A [i][j] = BA + w * [ n * ( i – Lr ) + ( j – Lc ) ]
Column-Major Order: The address of a location in Column Major System is
calculated as:
Address of A [i][j] = BA + w * [( i – Lr ) + m * ( j – Lc )]
Where:
BA = Base Address
i = Row subscript of element whose address is to be found
j = Column subscript of element whose address is to be found
w = Storage Size of one element stored in the array (in byte)
Lr = Lower limit of row/start row index of matrix, if not given assume 0 (zero)
Lc = Lower limit of column/start column index of matrix, if not given assume 0 (zero)
m = Number of row of the given matrix
n = Number of column of the given matrix
Important: Usually number of rows and columns of a matrix are given (like A[20][30] or
A[40][60] ) but if it is given as A[Lr- – – – – Ur, Lc- – – – – Uc]. In this case number of rows
and columns are calculated using the following methods:
Column-Major :
The given values are: BA = 1500, w = 1 byte, i = 15, j = 20, Lr = -15, Lc = 15, m = 26
Address of A [ i ][ j ] = BA + w * [( i – Lr ) + m * ( j – Lc )]
= 1500 + 1* [(15 – (-15)) + 26 * (20 – 15) + ]
= 1500 + 1 * [30 + 26 * 5] = 1500 + 1 * [160] = 1660
Row-Major:
The given values are: B = 1500, W = 1 byte, i = 15, j = 20, Lr = -15, Lc = 15, N = 26
Address of A [ i ][ j ] = BA + w * [ n * ( i – Lr ) + ( j – Lc ) ]
= 1500 + 1* [26 * (15 – (-15))) + (20 – 15)]
= 1500 + 1 * [26 * 30 + 5] = 1500 + 1 * [780 + 5] = 1500 + 785 = 2285
The exact size of array is unknown until the compile time i.e. time when a compiler compiles code
written in a programming language into a executable form. The size of array you have declared
initially can be sometimes insufficient and sometimes more than required.
What?
The process of allocating memory during program execution is called dynamic memory allocation. It
also allows a program to obtain more memory space, while running or to release space when no
space is required.
struct Book
{
char name[10];
int price;
}
int main()
{
struct Book a; //Single structure variable
struct Book* ptr; //Pointer of Structure type
ptr = &a;
An abstract data type (ADT) is a mathematical model for data types where a data
type is defined by its behavior (semantics) from the point of view of a user of the
data, specifically in terms of possible values, possible operations on data of this
type, and the behavior of these operations. When considering Array ADT we are
more concerned with the operations that can be performed on array.
Insertion Deletion
Insert operation is to insert one or more data elements Deletion refers to removing an existing element from
into an array. Based on the requirement, new element the array and re-organizing all elements of an array.
can be added at the beginning or end or any given
position of array. Consider LA is a linear array with N elements and K is
a positive integer such that K<=N. Below is the
Let LA is a Linear Array (unordered) with N elements and algorithm to delete an element available at the Kth
K is a positive integer such that K<=N. Below is the position of LA. Procedure - DELETE(LA, N, K)
algorithm where ITEM is inserted into the Kth position of
LA. Procedure – INSERT(LA, N, K, ITEM) 1. Start
2. Set J = K
1. Start
3. Repeat step 4 while J < N
2. Set J=N
4. Set LA[J] = LA[J+1] /* Move the element upward*/
3. Set N = N+1 /* Increase the array length by 1*/
5. Set N = N-1 /* Reduce the array length by 1 */
4. Repeat steps 5 and 6 while J >= K
6. Stop
5. Set LA[J+1] = LA[J] /* Move the element downward*/
6. Set J = J-1 /* Decrease counter*/
7. Set LA[K] = ITEM
8. Stop
Search Updation
You can perform a search for array element Update operation refers to updating an existing
based on its value or position. element from the array at a given position.
Consider LA is a linear array with N elements. Consider LA is a linear array with N elements
Below is the algorithm to find an element with a and K is a positive integer such that K<=N.
value of ITEM using sequential search. Below is the algorithm to update an ITEM
Procedure - SEARCH(LA, N, ITEM) available at the Kth position of LA. Procedure -
UPDATE(LA, N, K, ITEM)
1. Start
2. Set J=1 and LOC = 0 1. Start
3. Repeat steps 4 and 5 while J < N
2. Set LA[K] = ITEM
4. IF (LA[J] = ITEM) THEN LOC = J AND GOTO STEP 6
3. Stop
5. Set J = J +1
6. IF (LOC > 0) PRINT J, ITEM ELSE PRINT ‘Item not
found’
7. Stop
Traversal Sorting
Traversal operation refers to printing the Sorting operation refers to arranging the elements
contents of each element or to count the number either in ascending or descending way.
of elements with a given property
Consider LA is a linear array with N elements. Below
Consider LA is a linear array with N elements. is the Bubble Sort algorithm to sort the elements
in ascending order. Procedure - SORT(LA, N)
Below is the algorithm to print each element.
Procedure - TRAVERSE(LA, N)
1. Start
2. Set I = 0
1. Start 3. Set J = 0
2. Set J=1 4. Repeat steps 5,6,7 and 8 while I < N
3. Repeat steps 4 and 5 while J < N 5. J = I + 1
4. PRINT LA[J] 6. Repeat steps 7 and 8 while j <N
5. Set J = J +1 7. IF LA[I] is > LA[J] THEN
8. Set TEMP = LA[I]; LA[I] = LA[J]; LA[J] = TEMP;
6. Stop
9. Stop
1. Start
/* Assignment1 */
2. Stop
Assignment 3 Assignment 4
LA is a linear array with N elements. Write the LA is a linear array with N elements. Write the
algorithm to finds the largest number and algorithm to copy the elements from LA to a
counts the occurrence of the largest number new array LB
1. Start 1. Start
/* Assignment 3 steps */ /* Assignment 4 steps*/
2. Stop 2. Stop
Assignment 5 Assignment 6
LA is a linear array with N elements. Write the LA is a linear sorted array with N elements.
algorithm to transpose the array Write the algorithm to insert ITEM to the array
1. Start 1. Start
/* Assignment 5 steps */ /* Assignment 6 steps */
2. Stop 2. Stop
Polynomial is an expression constructed from one or more variables and constants, using only the
operations of addition, subtraction, multiplication, and constant positive whole number exponents.
A term is made up of coefficient and exponent.
Examples –
Polynomial with single variable P(X) = 4X3 + 6X2+7X+9 (4,6,7 are coefficient & 3,2 are exponent)
Polynomial with 2 variables P(X, Y) = X3 - 2XY +1 (2 is coefficient & 3 is exponent)
Definition–
Polynomial with single variable P(X) =
A polynomial thus may be represented using arrays. Array representation assumes that the exponents of the
given expression are arranged from 0 to the highest value (degree), which is represented by the subscript of the
array beginning with 0. The coefficients of the respective exponent are placed at an appropriate index in the
array. Considering single variable polynomial expression, array representation is
Consider LA is a linear array with N elements and LB is a linear array with M elements.
Below is the algorithm for polynomial addition
1. Start
2. Set j= maximum of M or N
3. Create a sum array LSum[] of size J
4. IF (N is Greater Than or Equal to M) Then
Copy LA[] to LSum[]
else
Copy LB[] to LSum[]
5. IF (N is Greater Than M) then
Traverse array LB[] and LSum[i] = LSum[i] + LB[i]
else
Traverse array LA[] and LSum[i] = LSum[i] + LA[i] while i < j
6. PRINT LSum
7. Stop
Given two polynomials represented by two arrays, below is the illustration of the
multiplication of the given two polynomials.
Example :
Input: A[] = {5, 0, 10, 6} and B[] = {1, 2, 4}
Output: prod[] = {5, 10, 30, 26, 52, 24}
The first input array represents "5 + 0x1 + 10x2 + 6x3"
The second array represents "1 + 2x1 + 4x2"
And output is "5 + 10x1 + 30x2 + 26x3 + 52x4 + 24x5”
5 0 10 6 Coefficents 1 2 4 0 Coefficents
A B
0 1 2 3 Exponents 0 2 2 3 Exponents
AXB
5 10 30 26 52 24 Coefficents
Prod
0 2 2 3 4 5 Exponents
Algorithm:
prod[0.. m+n-1] Multiply (A[0..m-1], B[0..n-1])
1. Start
2. Create a product array prod[] of size m+n-1.
3. Initialize all entries in prod[] as 0.
4. Travers array A[] and do following for every element A[i]
Traverse array B[] and do following for every element B[j]
prod[i+j] = prod[i+j] + A[i] * B[j]
5. return prod[]
6. Stop
Class Exercise
Suppose A and B are two matrices and their order are respectively m x n and p x q. i, j and k are counters. And C to
store result.
Step 1: Start.
Step 2: Read: m, n, p and q
Step 3: Read: Inputs for Matrices A[1:m, 1:n] and B[1:p, 1:q].
Step 4: If n ≠ p then:
Print: Multiplication is not possible.
Else:
Repeat for i := 1 to m by 1:
Repeat for j := 1 to q by 1:
C[i, j] := 0 [Initializing]
Repeat k := 1 to n by 1
C[i, j] := C[i, j] + A[i, k] x B[k, j]
[End of for loop]
[End of for loop]
[End of for loop]
[End of If structure]
Step 5: Print: C[1:m, 1:q]
Step 6: Stop
In this representation, only non-zero values are considered along with their row and column index
values. In this representation, the 0th row stores total rows, total columns and total non-zero values
in the matrix. For example, consider a matrix of size 5 X 6 containing 6 number of non-zero values.
This matrix can be represented as shown in the image...
2 D Array Row Representation
2D array is used to represent a sparse matrix in which there are three
columns named as
• Rows: Index of row, where non-zero element is located
• Columns: Index of column, where non-zero element is located.
• Values: Value of the non zero element located at index – (row,
column)
In above example matrix, there are 6 non-zero elements ( those are 9, 8, 4, 2, 5 & 2) and matrix size is 5 X 6. We
represent this matrix as shown in the above image. The first row is filled with values 5, 6 & 6 which indicates that
it is a sparse matrix with 5 rows, 6 columns & 6 non-zero values. Second row is filled with 0, 4, & 9 which
indicates the value in the matrix at 0th row, 4th column is 9. In the same way the remaining non-zero values also
follows the similar pattern.
Rows 5 0 1 2 2 3 4
Columns 6 4 1 0 2 5 2
Values 6 9 8 4 2 5 2
2D array is used to represent a sparse matrix in which there are three rows named as
• Rows: Index of row, where non-zero element is located
• Columns: Index of column, where non-zero element is located.
• Values: Value of the non zero element located at index – (row, column)
In above example matrix, there are 6 non-zero elements ( those are 9, 8, 4, 2, 5 & 2) and matrix size
is 5 X 6. We represent this matrix as shown in the above image. The first column is filled with
values 5, 6 & 6 which indicates that it is a sparse matrix with 5 rows, 6 columns & 6 non-zero
values. Second column is filled with 0, 4, & 9 which indicates the value in the matrix at 0th row, 4th
column is 9. In the same way the remaining non-zero values also follows the similar pattern.
Assignment 7 Assignment 8
Write an algorithm to add the original sparse Write an algorithm to multiply two sparse
matrix with the transpose of the same matrix. matrices.
1. Start 1. Start
/* Assignment 7 steps */ /* Assignment 8 steps*/
2. Stop 2. Stop
Assignment 9 Assignment 10
9.1. Design an efficient data structure to store Design an algorithm to convert a lower
data for lower and upper triangular matrix. triangular matrix to upper triangular matrix.
1. Start
9.2. Design an efficient data structure to store /* Assignment 10 steps */
data for tri-diagonal matrix. 2. Stop
11. Write an algorithm that takes as input the size of the array and the elements
in the array and a particular index and prints the element at that index.
12. Write down the algorithm to sort elements by their frequency.
13. Write down the algorithm to add two polynomials of single variable.
14. Write down the algorithm to multiply two polynomials of two variables.
15. A program P reads in 500 random integers in the range [0..100] presenting
the scores of 500 students. It then prints the frequency of each score above
50. What would be the best way for P to store the frequencies?
16. Write down the algorithm to delete all the vowels in a character array.
17. Write down the algorithm to print all the elements below the minor diagonal
in a 2-D array.
18. Write an algorithm to find a triplet that sum to a given value
19. Given an array arr, write an algorithm to find the maximum j – i such that
arr[j] > arr[i]
20. Write an algorithm to replace every element in the array with the next
greatest element present in the same array.
School of Computer Engineering
Assignments cont…
36
21. Write an algorithm that takes as input the size of the array and the elements
in the array and find the median of the elements in the array.
22. Write an algorithm that takes as input the size of the array and the elements
in the array and find the mode of the elements in the array.
23. Lower Triangular array –
• What is the maximum number of non-zero elements?
• How the elements can be stored sequentially in memory?
• Develop an algorithm for accessing the array[i][j] where i>=j
24. Upper Triangular array –
• What is the maximum number of non-zero elements?
• How the elements can be stored sequentially in memory?
• Develop an algorithm for accessing the array[i][j] where i<=j
25. Check board –
• How a check board can be represented by array?
• How to represent the state of a game of checkers at a particular instant?
8. Given an unsorted array, Write down the algorithm to find the minimum difference
between any pair in given array.
Input : {1, 5, 3, 19, 18, 25};
Output : 1 as Minimum difference is between 18 and 19
9. Given an array of integers, Write down the algorithm to count number of sub-arrays
(of size more than one) that are strictly increasing.
Input: arr[] = {1, 2, 3, 4}
Output: 6 as there are 6 sub-arrays {1, 2}, {1, 2, 3}, {1, 2, 3, 4}, {2, 3}, {2, 3, 4} and {3,
4}
10. Given an array of integers. All numbers occur twice except one number which occurs
once. Write down the algorithm to find the number in O(n) time & constant extra
space.
Input: ar[] = {7, 3, 5, 4, 5, 3, 4};
Output: 7
11. Given a 2D array of size m X n, containing either 1 or 0. As we traverse through,
where ever we encounter 0, we need to convert the whole corresponding row and
column to 0, where the original value may or may not be 0. Devise an algorithm to
solve the problem minimizing the time and space complexity.
School of Computer Engineering
Supplementary Reading
40
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]#axzz4myAupUvT
[Link]
svVJH9p
What is Array?
Array is a collection of variables of same data type that share a common
name.
Array is an ordered set which consist of fixed number of elements.
Array is an example of linier data structure.
In array memory is allocated sequentially so it is also known as
sequential list.
1-D Array address calculation
Address of A[i] = BA + w * (i) where BA is the base address, w is the word
length and i is the index
Row-Major order: Row-Major Order is a method of representing multi
dimension array in sequential memory. In this method elements of an array
are arranged sequentially row by row. Thus elements of first row occupies
first set of memory locations reserved for the array, elements of second row
occupies the next set of memory and so on.
Address of A [ i ][ j ] = BA + w * [ n * ( i – Lr ) + ( j – Lc ) ]
School of Computer Engineering
FAQ
42
Ragged 2 D Arrays:
char *font[] = {
(char []) {65,8,12,1,0,0x18, 0x3C, 0x66, 0xC3, 0xC3, 0xC3, 0xC3, 0xFF, 0xFF},
(char []) {39,2,3,4,9,0xC0,0xC0, 0xC0},
(char []) {46,2,2,4,0,0xC0,0xC0}};