D.S Notes
D.S Notes
Structures
DATA
Data can be in the form of numbers,
characters, symbols, or even pictures
CHENNAI
NEETHA
INFORMATION:
It is a processed data (collection of data)
which is having perfect meaning
• Entity: Any object that has certain attributes or properties which may
be assigned values.
• Eg: The employee of an organization.
Attributes Values
Name : John
Age : 33
Gender : Male
Emp.ID : 13472
Entity Set
Employee Details
Emp ID Name Age Gender
13472 John 33 Male
13583 Mary 32 female
Entity Set
13467 Rahul 31 Male
Data type
• A data type specifies what type of value, a variable can be
assigned in computation or processing.
• Trees : stores the information in hierarchy style, (data items are arranged in
branches and sub branches)represented by vertices connected by edges.
Eg: Binary Tree, B-Tree.
Difference - Linear and Non Linear Data Structure
Linear Data Structure Non-Linear Data Structure
• Searching: Finding the location of the data/record with a given key value.
• Merging: Combining the data or records in two different sorted files into a single sorted
file.
Data Structures Operations on Arrays
• Traversing: Accessing and processing each data or record exactly once.
25
23 27
25 29
27 31
29 32
30 34
32 37
35 39
37 41
39 42
40
0 1 2 3 4 5 6 7 8 9
Data Structures Operations on Arrays
• Searching: Finding the position of the number with a given search value.
• Find the location of 67
67 67 67 67 67
= = = = =
22 32 44 52 67 15 90 87 37 40
0 1 2 3 4 5 6 7 8 9
Index no 4
position 5
Data Structures Operations on Arrays
• Inserting: Adding a new record to the data structure.
• Insert 12 at the index location 3.
12
22 32 44 52
12 67
52 67
0 1 2 3 4 5 6 7 8 9
Data Structures Operations on Arrays
• Deleting: Removing a data (number) from the data structure.
• Delete 12 at the index location 3.
22 32 44 52
12 67
67
52 67
0 1 2 3 4 5 6 7 8 9
Data Structures Operations on Arrays
• Sorting: Arranging the data (elements) in some logical order.(ascending or descending)
33 25 27 29 30 32 35 37 39 40
0 1 2 3 4 5 6 7 8 9
25 27 29 30 32 33 35 37 39 40
0 1 2 3 4 5 6 7 8 9
Data Structures Operations on Arrays
• Merging: Combining the elements in two different sorted files into a single sorted file.
1 3 5 7 9 2 4 6 8 10
0 1 2 3 4 0 1 2 3 4
1 2 3 4 5 6 7 8 9 10
0 1 2 3 4 5 6 7 8 9
Abstract Data Types
• The abstract datatype is special kind of datatype, whose
behavior is defined by a set of values and set of operations.
• Time complexity measures the time taken to execute each statement of code in an
algorithm. If a statement is set to execute N times then,
• Time complexity = N x (the time required to run that line or function one time).
• The relation between the input data size (n) and number of operations
performed (N) with respect to time is denoted as Order of growth in Time
complexity.
Space Complexity (Space Efficiency)
• The space complexity can be defined as amount of memory required by an algorithm
to run.
• Space efficiency depends on the following factors:
Or
• Decrease the space required to store the data, by increasing the running
time of an algorithm.
Sequential or Linear Search
Linsearch(n,a,S)
22
=
22 32 44 52 67 15 90 87 37 40
0 1 2 3 4 5 6 7 8 9
22 32 44 52 67 15 90 87 37 40
40
0 1 2 3 4 5 6 7 8 9
Average=(1+2+3+4+5+6+7+8+9+10)/10
No:of Comparisions
IfIfIfSSS==37
=67
52
=87
==15
44
32
=90
=22 No:of
No:of Comparisions
Comparisions =8
=7
=9
=5
=3
=6
=2
=4
=1 22 37
=10 22 32 44 52
52 67 15 90 87 40
0 1 2 3 4 5 6 7 8 9
Complexity of Linear Search
• The time required to execute the algorithm is given by the
number of comparisons C, between S and a[i].
• Eg: In sequential search the best case is if the search element is first element in the
array.
Worst-case efficiency
• Worst case is the case of maximum value of f(n), time/space complexity of
an algorithm , among all possible inputs of size n.
• Eg: In sequential search the worst case is , if the search element not found or if it is
the last element in the array.
Average case efficiency
• Average of the time taken to solve all the possible (random) instances of
the input of size n.
• The O (big oh), Ω (big omega), ʘ (big theta), o (little oh), (little omega) are
the asymptotic notations used to indicate ,compare and rank the order of
growth of an algorithm.
Big Oh- O notation
• The “big O” notation defines an upper bound for the function f(n).
f(n) ∈ O(g(n)) read as “f(n) is an element of O of g(n)”
• Function f(n) is bounded above by C multiples of g(n) where C is a positive
number and n is a positive integer > n0,
f(n) <= C * g(n)
• f(n) is a function whose growth rate is asymptotically less than or equal to the
C *( g( n) ) function.
Worst case time complexity of linear search is O(n) ,and that for Binary search is O(log n).
Big Oh- O notation
• For all values n to the right of n0, the value of the function f(n) is on or
below c*g(n).
Little oh –o notation
• o notation is used to denote an upper bound that is strictly less than C *( g( n) )
function.
f(n) < C * g(n) for all n > n0.
• f( n ) is a function whose growth rate is strictly less than C *( g( n) ) function.
f(n) ∈o(g(n))
• Implies that for any positive constant C and positive integer n>n0, f(n) < C*g(n)
f(n)
Big Omega- Ω notation
• The “big Ω” notation defines a lower bound for the function f(n).
• f(n) ∈ Ω(g(n)) read as “f(n) is omega of g(n)”
• Function f(n) is bounded below by C multiples of g(n) for all values of n> n0,.
f(n) >= C * g(n) for all n > n0,
• f(n) ∈ ʘ (g (n)), implies f(n) is bounded both above and below by some
constant multiple of g (n) for all n> n0,
• f(n) = ʘ (g (n))
• “f(n) is theta of g(n)”, If there exist two positive constant C1 and C2 and
positive integer n>n0 such that
C1 * g (n) <= f (n) <= C2 * g (n)
Big Theta - Ѳ notation
f(n)
For all values of n to the right of n0, the value of f(n) lies at or above C2*g(n) and at or below
C1*g(n).
g(n) is an tight upper and lower bound for f(n).
Important Questions
• Define algorithm. Explain the characteristics of an algorithm.
• Define the terms Space complexity, time complexity.
• Illustrate asymptotic notations with examples.
Chapter 3
Preliminaries
Mathematical Notations and Functions
• Remainder Function : Modular Arithmetic
• Floor and Ceiling Function
• Integer and Absolute Value function
• Summation
• Permutations
• Exponents and Logarithms
M X Q + R = K
Eg: 35 mod 6 = 5
6 x 5 + 5 = 35
25 mod 5=0. (Remainder 0)
5 X 5 +0=25
3 mod 5=3
5X0 + 3=3
Ms. Benita Jaison, Dept. of CSA, St. Francis College.
Arithmetic modulus
• Arithmetic modulus M refers to the arithmetic operations
of addition , multiplication and subtraction where the
result is replaced by it’s equivalent value in set,with respect
to each modulus M.
1–5= ?
1-5 = -4 mod 12 = 8
Eg: 25 ≡7 mod 3
25 mod 3=7 mod 3
25 ≡7 mod 3 , if and only if (25-7) is completely divisible by 3.
Ms. Benita Jaison, Dept. of CSA, St. Francis College.
Consider a real number 3.6
Integer greater than 3.6 are 4,5,6..etc.
4 Least integer which is greater than 3.6 is
4,which is considered as the ceiling(3.6)
3.6
-3
e.g. floor(2.6) = 2
floor(–2.1) = –3
Eg ceiling(2.6) = 3
ceiling(–2.1) = –2.
• Notation: x = ceiling(x).
• If x is itself integer then x = x
• If x is real number then x +1 = x
∑a j
where j=1,2,3,….
• The letter j in the above expression is called a dummy index or dummy variable.
• Sum of squares of numbers 22+32+42+52 can be represented using ∑ and the dummy
variable j where j value range from 2 to 5 as
• Factorial is the product of the positive integers from 1 to n, inclusive and is denoted
by n!.
• n!=1 x 2 x 3 x….x (n-2)x (n-1) x n
• Eg: The permutations of the set consisting of the elements a,b,c are as follows:
abc, acb, bac, bca, cab, cba
Disadvantages are
➢ Records may require more space than the length fixed for each record
➢ Correction of few characters may require the entire record to be
changed
➢ Inserting a new record may require records to be moved to new memory
location.
Fixed length storage using linear array pointer
• Record are not stored in consecutive memory location.
• A linear array of pointer stores the address of each successive record.
Array pointer
data pointer
B S c
Head: pointer to the first node The last node points to NULL
Advantages and Disadvantages of Linked Storage
Adv:
• Can easily insert, delete, concatenate and rearrange
substrings when using a linked storage.
Disadv:
• Additional space is used for storing the links.
• One cannot directly access a character in the middle of the
list.
String as ADT
• An abstract data type (ADT) is special kind of datatype which consists of a set
of data values, a defined set of properties of for values and the operations that
are applicable for the datatype, hiding the implementation details.
• The string ADT values are, sequences of characters upto a specified length.
• String properties : String is made up of ASCII characters set, having length varying from
0 to specified length.
• String operations are used for processing the values.
String as ADT
Operations allowed on a string: a c a b a b c
0 1 2 3 4 5 6
• Return the nth character in a string - GETCHAR (str, n)
• Set the nth character in a string to c – PUTCHAR (str , n , c)
• Concatenate two strings – CONCAT(str1, str2)
• Compare string – COMPARE(str1, str2)
• Find the length of a string - LENGTH(str)
• Return the Index of the 1st occurrence of a character in text. INDEX (text , pattern)
• Return the position of 1st occurrence of character in text. POS (text , pattern).
• Return a substring of str of length m, starting at the position i SUBSTRING (str, i , m)
• Delete a substring from str of length m, starting at the position i– DELETE (str, i, m)
• str1 inserted to str2 at position i - INSERT(str1, str2, i)
• Replace a character1 in text with character2 -REPLACE (text, char1 , char2)
String Operations
• Concatenation - joining two strings end to end.
• CONCAT(S1, S2) Requires the name of 2 strings.
• The string , consisting of the characters of S11 followed by the characters of S2 is
called concatenation of S1 and S2.
eg:.S1=“MCA”,S2=“DEPT”
CONCAT(S1,S2) =“MCADEPT".
• T (text) and P(pattern) are stored as arrays of characters. Algorithm finds the
INDEX of P in T.
• Compare a given pattern P with each of the substring of T, moving from left to
right, until we get a match.
• If N is the length of the Text and M is the length of Pattern, then no:of
substring possible is given as, S=N-M+1.
The Brute Force Method of Pattern Matching Algorithm
a c a b a b c T[ ] Text of length N=7
0 1 2 3 4 5 6
a b c
0 1 2 P[ ] Pattern of length M=3
a b c a b c a b c
0 1 2 0 1 2 0 1 2
First Shift
i determines the shift or substring number
j determines the character in each substring
T[ i+j ]==P[j]
i=0
T[n ] a c a b a b c
0 1 2 3 4 5 6
J=0 J=1
a b c
P[m]
0 1 2
The Brute Force Method of Pattern Matching Algorithm
T[ j+i ] i=0
T[ j+i ] i=2
a c a b a b c a c a b a b c
0 1 2 3 4 5 6 0 1 2 3 4 5 6
J=0 J=1 J=0 J=1 J=2
P[j] a b c P[j] a b c
0 1 2 0 1 2
a b c
0 1 2
Pattern P[ ]=a b c d
Length of pattern, M=4
• If the first trial fails, it shifts the pattern to the right. The
comparisons within a shift, that the algorithm does is from
right to left,
Boyer-Moore algorithm
• The Boyer-Moore algorithm precompute the shift size.
• Shift size by considering two quantities from the
preprocessed information.
• Bad‐symbol table indicates how much to shift based on the
text’s character that causes a mismatch
• Good‐suffix table indicates how much to shift based on
matched part (suffix) of the pattern
Function Action
strcat() Concatenates 2 strings
strcmp() Compares 2 strings
strcpy() Copies one string over
another
strlen() Finds the length of a string
STRING HANDLING FUNCTIONS
strlen()
• strlen() function takes string name as parameter and returns the length of
string.
strcpy()
• strcpy() takes 2 strings and copies the content of one string to the content of
another string.
strcat() denoted as ‘||’
• strcat() takes 2 strings and concatenate (joins) two strings.
• Resultant string is stored in the first string specified in the argument
strcmp()
• strcmp() takes two string and returns value 0, if the two strings are equal.
String Copy without using string function strcpy()
char s1[10], s2[10];
int i;
clrscr();
printf("\nEnter the string :");
gets(s1);
i = 0;
while (s1[i] != '\0') {
s2[i] = s1[i];
i++;
}
s2[i] = '\0';
printf("Original string in s1 is %s",s1);
printf("\nCopied String in s2 is %s ", s2);
getch();
Deleting every occurrence of P in T
Algorithm
Input :Text T and pattern P
Output: Returns text T, after deleting every occurrence of P in T
1. Repeat step 2 to 4 while (pos!=-1)
2. pos=INDEX(T,P)
3. L=LENGTH(P)
4. T=DELETE(T,pos,L)
5. Write T
Replacing every occurrence of P in T
Algorithm
Input :Text T and pattern P
Output: Returns text T, after replacing every occurrence of P in T
1. Repeat step 2 to 4 while (pos!=-1)
2. pos=INDEX(T,P)
3. L=LENGTH(P)
4. T=REPLACE(T,pos,L)
5. Write T
ARRAYS
Chapter 5
• Eg:
• int a[10]; //integer array
• char a[10]; //character array
Arrays
• Each Programming language has its own rules for declaring arrays.
• Declaration must implicitly or explicitly provide 3 types of information:
• The name of the array
• The data type of the array
• The index of the array
• Some programming languages (eg:FORTRAN) allocate memory space for arrays
statically during the compilation of the program.
• While some languages allocate (eg:C ) can also allocate memory space
dynamically by accepting the size and then declaring array with n elements.
• int a[10]; //Static allocation
• int *a; // Dynamic allocation
• a=(int *)malloc( n* sizeof(int))
Arrays
0 1 2 3 4 5
2078
2 8 5 12
12 9 44
0 1 2 3 4 5 6 7 8 9
i>= ind
2 >=3 3 >=3 4 >=3 5 >=3
i-- i-- i--
Deleting
• Deleting refers to the operation of removing one elements from the
array A[].
• Deleting an element at the end of an array does not require much
changes.
• But deleting an element in the middle requires moving one location
towards left in order to fill up the array.
Deleting
Input : An array a[] of with n no:of elements , index position IndPos of the number
to be deleted.
Output :Value Val at index position IndPos deleted.
Delete (a, n, IndPos)
1. Set Val=a[IndPos]
2. i=IndPos
3. Repeat step 4 and 5 while (i <n-1)
4. Set a[i] =a[i+1]
5. i=i+1
6. Set n=n-1
7. Print “Val Deleted”
8. Exit
Int a[10] Deletion
n=6 Indpos=3
n=6 -1 =5 i=indpos=3
val =a[Indpos]
a[i]=a[i+1] a[i]=a[i+1]
val =
2 8 5 12
12 9 4
0 1 2 3 4 5 6 7 8 9
i< n-1
3 <5 4 <5 5 <5
i++ i++
Sorting
• Sorting refers to the operation of rearranging the elements of
an array a[] so that they are in increasing or decreasing order.
• Suppose a[] has the following elements 8,4,19,2,7,13,5,16.
• After sorting the array in ascending a[] becomes
2,4,5,7,8,13,16,19.
• After sorting the array in descending a[] becomes
19,16,13,8,7,5,4,2.
Bubble Sort
• Bubble sort is a simple comparison-based algorithm in
which a pair of adjacent elements is compared at a time
and the elements are swapped if they are not in
order.
• Each iteration through the array places the next largest
value in its proper place.
• Largest number “bubbles” up to the location where it
belongs.
• Bubbled up item are avoided for the next iteration.
Bubble sort
• Suppose the list of number a[1], a[2]…a[n] is in memory.
• Bubble Sort Algorithm
• Step 1: compare adjacent elements and arrange such that largest element
is bubble up to the a[n-1] position and involves n-1 comparisons.
• Step 2: Repeat step 1 with one less comparison; largest element is bubble
up to the a[n-2] position and involves n-2 comparisons. …..
• …..
• Step n-1: compare a[1] with a[2] and arrange them so that a[1] < a[2].
After this steps, the list will be sorted in increasing order.
First Iteration
temp= 12
i=0
j=0
12
12 88 5 3 9 4 1
j j+1
0 1 2 3 4 5 6
Algorithm
Input : Array a[] of size n
Output :Sorted elements in the array
BUBBLESORT (a[],n)
1. Repeat step 2 for i=0 to i< n-1
2. Repeat step 3 and 4 for j=0 to j< n-1 -i
3. If a[j]>a[j+1]
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
4. j=j+1
5. Exit
Complexity of Bubble Sort
n=8
void bubsort(int a[]) No:of iterations is 7 (0 to i<n-1)
No:of comparisons in each iterations is (0 to n-1-i)
{ 1st iteration 8-1-0 =7
for (i = 0; i < n-1; i++) Comparing 2nd iteration 8-1-1=6
3rd iteration 8-1-2=5
for (j = 0; j < n-1-i; j++) 4th iteration 8-1-3 =4
if (a[j] > a[j+1]) 5th iteration 8-1-4=3
6th iteration 8-1-5=2
{ Swapping 7th iteration 8-1-6=1
temp=a[j];
Total comparisons = 7+6+5+4+3+2+1
a[j]=a[j+1]; =(n-1)+(n-2)+(n-3)+(n-4)+…+3+2+1
a[j+1]=temp; Sum of the series, S== n⁄2 (a + L)
=n/2(n-1+1)=n/2 * n
} =n2/2
=O(n2)
In each comparison , if a[j]>a[j+1] then swap operation.
Basic operation are comparison and swapping.
Best Case Time Complexity
• If the numbers are already sorted in ascending order, the
algorithm will determine in the first iteration that no number
pairs need to be swapped and can be terminated immediately.
• The algorithm must perform n-1 comparisons:
• The best-case time complexity of Bubble Sort is: O(n)
Worst and Average Case Time Complexity
Min=0
22 12 34 14 10
10
22
Min
0 1 2 3 4
Second Iteration
Min=1
10 12 34 14 10
22
0 Min
1 2 3 4
Third Iteration
Min=2
10 12 3434 14 22
0 1 Min
2 3 4
Fourth Iteration
Min=3
10 12 14 34
34 22
22
0 1 2 Min
3 4
Algorithm
Input : Array a[] of size n
Output :Sorted elements in the array
SELECTIONSORT (a[],n)
1. Repeat step 2 to step 5 for i=0 to n-1
2. Min=i
3. Repeat step 4 and 5 for j=i+1 to j<n
4. If a[j]<a[Min]
5. Min=j
6. Temp=a[i]
a[i]=a[min]
a[min]=Temp
7. Exit
Best case of Selection sort
• Selection Sort is an easy-to-implement,
• Selection sort has an average, best-case, and worst-case time
complexity of O(n²).
• Selection Sort is slower than Insertion Sort,
• The best case is the case when the array is already sorted.
• As swapping at each step can be avoided but the time spend to
find the smallest element is still O(N). Hence, the best case has:
• N * (N+1) / 2 comparisons
• 0 swaps
Worst case of Selection sort
• The worst case is the case when the array is already sorted in
descending order.
• The cost in this case is that at each step, a swap is done. This
is because the smallest element will always be the last element
and then the second smallest element that is the smallest
element of the new unsorted sub-array. Hence, the worst case
has:
• N * (N+1) / 2 comparisons
• N swaps
• Hence, the time complexity is O(N^2).
Average case of Selection sort
• Based on the worst case and best case, we know that the
number of comparisons will be the same for average case as
well, the number of comparisons will be constant.
• Number of comparisons = N * (N+1) / 2
• Therefore, the time complexity will be O(N^2).
• The number of swaps, is N swaps
Insertion Sort
• Insertion sort is the sorting mechanism where the sorted array is
built using one item at a time.
• For the 1st iteration the element at index 1, is set as the key
element.
• The key elements is compared with the sorted elements on the left
sequentially and then inserted in the current position in the list.
• The analogy is same as we arrange a deck of cards.
• This sort works on the principle of inserting an element at a
particular position, hence the name Insertion Sort.
Algorithm
Input : Array a[] of size n
Output :Sorted elements in the array
INSERTIONSORT (a[],n)
1. Repeat step 2 to step 7 for i=1 to i<n
2. key=a[i];
3. j=i-1;
4. Repeat step 5 to step 6 until j>=0 and a[j]>key
5. a[j+1]=a[j];
6. j=j-1;
7. a[j+1]=key;
First Iteration
a[j+1]=a[j]
9>5 j—
i=1 J=-1
Key= 5 a[j]>Key a[j+1]=Key Exit loop
j=i-1 =0
99 5 1 4 10
j i
0 1 2 3 4
Second Iteration
9>1 a[j+1]=a[j]
i=2
Key= 1 a[j]>Key
j=i-1 =1 a[j]=Key
5 9 1 4 10
j i
0 1 2 3 4
Third Iteration
a[j+1]=a[j]
9>4
i=3 a[j]>Key
a[j]=Key
Key= 4
j=i-1 =2
1 95 9 4 10
j i
0 1 2 3 4
Fourth Iteration
4 >10
i=4 a[j]>Key Exit the while loop
Key= 10
J=i-1 =3
1 94 95 9 10
j i
0 1 2 3 4
Difference between Bubble, Selection and Insertion Sort
• Bubble sort finds the largest number and “bubbles” up it to the last
location, then finds the 2nd largest element and take it last but position
and continues till array is sorted.
• Selection sort is the sorting algorithm that finds the smallest
element in the array and exchanges the element with the first
position, then find the second smallest element and exchange it
with 2nd position and continues till array is sorted.
• The insertion sort is the sorting algorithm that sorts by inserting the
an element into an existing sorted file.
Complexity of Insertion Sort
• The worst-case time complexity of Insertion Sort is when the
array elements are sorted in descending order and it is given
as : O(n²)
• Best-Case Time Complexity If the elements already appear in
sorted order, there is precisely one comparison in the inner
loop and no swap operation at all. The best-case time
complexity of Insertion Sort is: O(n)
• The average time complexity of Insertion Sort is: O(n²)
Divide and Conquer Approach
• Max heap if the value in parent node is greater than the values in its two children
nodes and Min heap if parent node is smaller.
• The process of reshaping a binary tree into a Heap data structure is known as
‘heapify’.
• Heapify procedure can be applied to a node only if its children nodes are heapified.
Heapification must be performed in the bottom-up order.
Steps for Heap Sort using Max Heap
1. Build a max heap from the input data.
2. The largest item is stored at the root of the heap.
3. Replace it with the last item of the heap followed by reducing the
size of heap by 1.
4. Heapify the root of tree.
5. Repeat above steps while size of heap is greater than 1.
Note :Heap Sort using max heap sorts in ascending order.
Steps for Heap Sort Using Min Heap
1. Build a min heap from the input data.
2. At this point, the smallest item is stored at the root of the heap.
3. Replace it with the last item of the heap followed by reducing the
size of heap by 1.
4. Heapify the root of tree.
5. Repeat above steps while size of heap is greater than 1.
Note :Heap Sort using min heap sorts in descending order.
Binary Tree: Array representation
0 1 2 3 4 5 6 7
11 89
11
Heap Sort
After deleting the root element, we again have to heapify it to convert it into max
heap.
Heap Sort
In the next step, to delete the root element (81) from the max heap,swap it with the last node, i.e. (54).
After deleting the root element, heapify it to convert it into max heap.
Heap Sort
Heap Sort
Heap Sort
ALGORITHM heapSort(int a[], int n)
1. Repeat step 2 for i = n / 2 – 1 to i >= 0 decrement i
2. heapify(a, n, i);
3. Repeat step 4 to 5 for i = n – 1 to i >= 0 decrement i
4. swap(&a[0],&a[i]);
5. heapify(a, i, 0);
ALGORITHM heapify(int a[], int n, int i)
1. large =i
2. lt 2 * i + 1
3. rt = 2 * i + 2
4. if (lt < n && a[lt] > a[large])
large = lt;
5. if (rt < n && a[rt] > a[large])
large = rt
6. if (large != i)
swap(&a[i],&a[large])
heapify(a, n, large)
Heap Sort Complexity and Efficency
• Time Complexity: Time complexity of heapify is O(Logn). Time
complexity of createAndBuildHeap() is O(n) and the overall time
complexity of Heap Sort is O(nLogn).
• Advantages of heapsort –
• Efficiency – The time required to perform Heap sort increases
logarithmically while other algorithms may grow exponentially slower
as the number of items to sort increases. This sorting algorithm is
very efficient.
• Memory Usage – Memory usage is minimal because apart from what
is necessary to hold the initial list of items to be sorted, it needs no
additional memory space to work
Searching
• Searching refers to the operation of finding the location of ITEM in array of
elements or printing not found if the item is not present.
• The search is successful, if the ITEM is found and unsuccessful otherwise.
• There are 2 types of searching algorithms. Binary search and linear search.
int A[10]
40 40 40 40 40 40 40 40 40
= = = = = = = = =
22 32 44 52 67 15 90 87 37 40
40
0 1 2 3 4 5 6 7 8 9
0<10 1<10 2<10 3<10 4<10 5<10 6<10 7<10 8<10 9<10
A[8] !=40
A[0] !=40 A[1] !=40 A[2] !=40 A[3] !=40 A[4] !=40 A[5] !=40 A[6] !=40 A[7] !=40 A[9] ==40
Binary Search
• Binary search is the most popular Search algorithm.
Binary search works only on a sorted set of
elements.
• Binary search begins by comparing the element in
the middle of the array with the search value.
• Index of middle element is calculated as index of( first
+ last )/2.
• The algorithm eliminates the half in which the
search value cannot be a part.
Binary Search
35 70 1 5 50 65 20
• Sort the elements in the array.
• Index of middle element is calculated First sort the elelments in the array
as index of( first + last )/2.
• Compare the element in the middle
of the array with the search value. first 50 last
Two dimensional Arrays are stored in the memory in the following two ways :
• Row-major representation .
• Column-Major representation.
Row Major ordering
• In row major ordering, all the rows of the 2D array are stored into the memory
contiguously.
0 1 2
0
If array is declared by a[m][n] where m is the number of rows while n is the number of columns, then
address of an element a[i][j] of the array stored in row major order is calculated as,
0 1 2
0
1
If array is declared by a[m][n] where m is the number of rows while n is the number of columns, then address
of an element a[i][j] of the array stored in row major order is calculated as,
The first dimension represents the row, second represent the column and the third represents the depth
Memory Representation of Multidimensional Arrays
• Row-major representation : The arrays are stored in the memory in row
design.First row is followed by the second row in the memory and so on.
• Location [i,j]=Base address(A)+{(i* colSize)+j}* (Sizeof datatype).
• First matrix, where all the entries above the main diagonal are zero and all
non zero entries can occur only on or below the main diagonal is called a
lower triangular matrix.
• The second matrix ,where non zero entries can occur on the diagonal or
on the elements immediately above or below the diagonal is called a
tridiagonal matrix.
Sparse matrix storage
• Representation of sparse matrices should store only
nonzero elements to save space.
• The non zero elements are represented by their row and
column number.
• Each element is characterized by <row, col, value>.
The sparse matrix
• The sparse matrix is represented by a two-dimensional array.
• Each element is characterized by <row, col, value>.
• The first row indicate the no:of rows and columns and total non-
zero values.
No:of Columns
No :of Rows Nonzero terms
transpose
Transpose a sparse matrix
• For all elements in each row i
• Element <i, j, value> is stored in element <j, i, value> of the transpose matrix.
• (0, 0, 15) ====> (0, 0, 15)
(0, 3, 22) ====> (3, 0, 22)
(0, 5, -15) ====> (5, 0, -15)
(1, 1, 11) ====> (1, 1, 11)
OR