SlideShare a Scribd company logo
 Linear arrays: Memory representation
 Traversal
 Insertion
 Deletion
 Linear Search
 Binary Search
 Merging
 2D Array : Memory representation
1
CONTENTS
2.1 Introductions
2.2 Linear Array
2.2.1 Linear Array Representations in Memory
2.2.2 Traversing Algorithm
2.2.3 Insert Algorithms
2.2.4 Delete Algorithms
2.2.5 Sequential and Binary Search Algorithm
2.2.6 Merging Algorithm
2.3 Multidimensional Array
2.3.1 2-D Array
2.3.2 Representations in Memory
2
2.1 Introduction
Data Structure can be classified as:
linear
non-linear
Linear (elements arranged in sequential in memory
location) i.e. array & linear link-list
Non-linear such as a tree and graph.
Operations:
Traversing, Searching, Inserting, Deleting, Sorting, Merging
Array is used to store a fix size for data and a link-list
the data can be varies in size.
3
2.1 Introduction
Advantages of an Array:
Very simple
Economy – if full use of memory
Random accessed at the same time
Disadvantage of an Array:
wasting memory if not fully used
4
2.2 Linear Array
 Homogeneous data:
a) Elements are represented through indexes.
b) Elements are saved in sequential in memory locations.
 Number of elements, N –> length or size of an array.
If:
UB : upper bound ( the largest index)
LB : lower bound (the smallest index)
Then: N = UB – LB + 1
Length = N = UB when LB = 1
5
2.2 Linear Array
 All elements in A are written symbolically as, 1 .. n is the
subscript.
A1, A2, A3, .... , An
 In FORTRAN and BASIC  A(1), A(2), ..., A(N)
 In Pascal, C/C++ and Java  A[0], A[1], ..., A[N-1]
 subscript starts from 0
LB = 0, UB = N–1
6
2.2.1 Representation of Array in a Memory
 The process to determine the address in a memory:
a) First address – base address.
b) Relative address to base address through index function.
Example: char X[100];
Let char uses 1 location storage.
If the base address is 1200 then the next element is in 1201.
Index Function is written as:
Loc (X[i]) = Loc(X[0]) + i , i is subscript and LB = 0
1200 1201 1202 1203
X[0] X[1] X[2]
7
2.2.1 Representation of Array in a Memory
 In general, index function:
Loc (X[i]) = Loc(X[LB]) + w*(i-LB);
where w is length of memory location required.
For real number: 4 byte, integer: 2 byte and character: 1 byte.
 Example:
If LB = 5, Loc(X[LB]) = 1200, and w = 4, find Loc(X[8]) ?
Loc(X[8])= Loc(X[5]) + 4*(8 – 5)
= 1212
8
2.2.2 Traversing Algorithm
 Traversing operation means visit every element once.
e.g. to print, etc.
 Example algorithm:
9
1. [Assign counter]
K=LB // LB = 0
2. Repeat step 2.1 and 2.2 while K <= UB // If LB = 0
2.1 [visit element]
do PROCESS on LA[K]
2.2 [add counter]
K=K+1
3. end repeat step 2
4. exit
2.2.3 Insertion Algorithm
 Insert item at the back is easy if there is a space. Insert
item in the middle requires the movement of all elements
to the right as in Figure 1.
0 1 2 3 4 k MAX_LIST-1
1 2 3 4 5 k+1 MAX_LIST
10
12 3 44 19 100 … 5 10 18 ? … ?
k+1
size
Array indexes New item
ADT list positions
items
Figure 1: Shifting items for insertion at position 3
2.2.3 Insertion Algorithm
 Example algorithm:
11
INSERT(LA, N, K, ITEM)
//LA is a linear array with N element
//K is integer positive where K < N and LB = 0
//Insert an element, ITEM in index K
1. [Assign counter]
J = N – 1; // LB = 0
2. Repeat step 2.1 and 2.2 while J >= K
2.1 [shift to the right all elements from J]
LA[J+1] = LA[J]
2.2 [decrement counter] J = J – 1
3. [Stop repeat step 2]
4. [Insert element] LA[K] = ITEM
5. [Reset N] N = N + 1
6. Exit
2.2.4 Deletion Algorithm
 Delete item.
(a)
0 1 2 3 4 k-1 k MAX_LIST-1
1 2 3 4 5 k k+1 MAX_LIST
12
12 3 44 100 … 5 10 18 ? … ?
k
size
Array indexes
Delete 19
ADT list positions
items
Figure 2: Deletion causes a gap
2.2.4 Deletion Algorithm
(b)
0 1 2 3 k-1 MAX_LIST-1
1 2 3 4 k MAX_LIST
13
12 3 44 100 … 5 10 18 ? … ?
k
size
Array indexes
ADT list positions
items
Figure 3: Fill gap by shifting
2.2.4 Deletion Algorithm
 Example algorithm:
14
DELETE(LA, N, K, ITEM)
1. ITEM = LA[K]
2. Repeat for I = K to N–2 // If LB = 0
2.1 [Shift element, forward]
LA[I] = LA[I+1]
3. [end of loop]
4. [Reset N in LA]
N = N – 1
5. Exit
2.2.5 Sequential Search
Compare successive elements of a given list with a search ITEM
until
1. either a match is encountered
2. or the list is exhausted without a match.
0 1 N-1
Algorithm:
SequentialSearch(LA, N, ITEM, LOC)
1. I = 0 // If LB = 0
2. Repeat step 2.1 while (i<N and LA[I] != ITEM )
2.1 I=I+1
3. If LA[I]==ITEM then
Return found at LOC=I
If not
Return not found 15
2.2.5 Binary Search Algorithm
 Binary search algorithm is efficient if the array is sorted.
 A binary search is used whenever the list starts to become large.
 Consider to use binary searches whenever the list contains more
than 16 elements.
 The binary search starts by testing the data in the element at the
middle of the array to determine if the target is in the first or
second half of the list.
 If it is in the first half, we do not need to check the second half. If
it is in the second half, we do not need to test the first half. In other
words we eliminate half the list from further consideration. We
repeat this process until we find the target or determine that it is
not in the list.
16
2.2.5 Binary Search Algorithm
 To find the middle of the list, we need three variables, one to
identify the beginning of the list, one to identify the middle
of the list, and one to identify the end of the list.
 We analyze two cases here: the target is in the list (target
found) and the target is not in the list (target not found).
17
2.2.5 Binary Search Algorithm
 Target found case: Assume we want to find 22 in a sorted
list as follows:
 The three indexes are first, mid and last. Given first as 0 and
last as 11, mid is calculated as follows:
mid = (first + last) / 2
mid = (0 + 11) / 2 = 11 / 2 = 5
18
4 7 8 10 14 21 22 36 62 77 81 91
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[10] a[11]
2.2.5 Binary Search Algorithm
 At index location 5, the target is greater than the list value (22 > 21).
Therefore, eliminate the array locations 0 through 5 (mid is automatically
eliminated). To narrow our search, we assign mid + 1 to first and repeat
the search.
19
4 7 8 10 14 21 22 36 62 77 81 91
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[10] a[11]
0 5 11
first mid last
Target: 22Target: 22
22 > 21
2.2.5 Binary Search Algorithm
 The next loop calculates mid with the new value for first and
determines that the midpoint is now 8 as follows:
mid = (6 + 11) / 2 = 17 / 2 = 8
20
4 7 8 10 14 21 22 36 62 77 81 91
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[10] a[11]
6 8 11
first mid last
Target: 22Target: 22
22 < 62
2.2.5 Binary Search Algorithm
 When we test the target to the value at mid a second time, we discover that the
target is less than the list value (22 < 62). This time we adjust the end of the list
by setting last to mid – 1 and recalculate mid. This step effectively eliminates
elements 8 through 11 from consideration. We have now arrived at index location
6, whose value matches our target. This stops the search.
21
4 7 8 10 14 21 22 36 62 77 81 91
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[10] a[11]
6 6 7
first mid last
Target: 22Target: 22
22 equals 228 6 7
function terminates
first mid last
2.2.5 Binary Search Algorithm
 Target not found case: This is done by testing for first and last crossing:
that is, we are done when first becomes greater than last. Two conditions
terminate the binary search algorithm when (a) the target is found or (b)
first becomes larger than last. Assume we want to find 11 in our binary
search array.
22
4 7 8 10 14 21 22 36 62 77 81 91
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[10] a[11]
0 5 11
first mid last Target: 11Target: 11
11 < 21
2.2.5 Binary Search Algorithm
 The loop continues to narrow the range as we saw in the
successful search until we are examining the data at index
locations 3 and 4.
23
4 7 8 10 14 21 22 36 62 77 81 91
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[10] a[11]
0 2 4
first mid last
Target: 11Target: 11
11 > 8
2.2.5 Binary Search Algorithm
 These settings of first and last set the mid index to 3 as follows:
mid = (3 + 4) / 2 = 7 / 2 = 3
24
4 7 8 10 14 21 22 36 62 77 81 91
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[10] a[11]
3 3 4
first mid last Target: 11Target: 11
11 > 10
2.2.5 Binary Search Algorithm
 The test at index 3indicates that the target is greater than the list value, so we set first to mid
+ 1, or 4. We now test the data at location 4 and discover that 11 < 14. The mid is as
calculated as follows:
 At this point, we have discovered that the target should be between two adjacent values; in
other words, it is not in the list. We see this algorithmically because last is set to mid – 1,
which makes first greater than last, the signal that the value we are looking for is not in the
list.
25
4 7 8 10 14 21 22 36 62 77 81 91
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[10] a[11]
4 4 4
first mid last
Target: 11Target: 11
11 < 14 4 4 3
first mid last
Function terminates
2.2.5 Binary Search Algorithm
 Example algorithm:
DATA – sorted array
ITEM – Info
LB – lower bound
UB – upper bound
ST – start Location
MID – middle Location
LAST – last Location
26
2.2.5 Binary Search Algorithm
27
1. [Define variables]
ST = LB, LAST= UB;
MID = (ST+LAST)/2;
2. Repeat 3 and 4 WHILE (ST <= LAST & DATA[MID] !=
ITEM)
3. If ITEM < DATA[MID] then
LAST = MID-1
If not
ST = MID+1
4. Set MID = INT((ST + LAST)/2)
[LAST repeat to 2]
5. If DATA[MID] == ITEM then
LOK = MID
If not
LOK = NULL
6. Stop
2.2.6 Merging Algorithm
Suppose A is a sorted list with r elements and B is a
sorted list with s elements. The operation that
combines the element of A and B into a single sorted
list C with n=r + s elements is called merging.
28
2.2.6 Merging Algorithm
Algorithm: Merging (A, R,B,S,C)
Here A and B be sorted arrays with R and S elements
respectively. This algorithm merges A and B into an array
C with N=R+ S elements
Step 1: Set NA=1, NB=1 and NC=1
Step 2: Repeat while NA ≤ R and NB ≤ S:
if A[NA] ≤ B[NB], then:
Set C[NC] = A[NA]
Set NA = NA +1
else
Set C[NC] = B[NB]
Set NB = NB +1
[End of if structure]
Set NC= NC +1
[End of Loop]
29
2.2.6 Merging Algorithm
Step 3: If NA >R, then:
Repeat while NB ≤ S:
Set C[NC] = B[NB]
Set NB = NB+1
Set NC = NC +1
[End of Loop]
else
Repeat while NA ≤ R:
Set C[NC] = A[NA]
Set NC = NC + 1
Set NA = NA +1
[End of loop]
[End of if structure]
Step 4: Return C[NC]
30
2.2.6 Merging Algorithm
Complexity of merging: The input consists of the
total number n=r+s elements in A and B. Each
comparison assigns an element to the array C, which
eventually has n elements. Accordingly, the number
f(n) of comparisons cannot exceed n:
f(n) ≤ n = O(n)
31
Exercises
Find where the indicated elements of an array a
are stored, if the base address of a is 200* and
LB = 0
a) double a[10]; a[3]?
b) int a[26]; a[2]?
*(assume that int(s) are stored in 4 bytes and
double(s) in 8 bytes).
32
2.3 MULTIDIMENSIONAL ARRAY
 Two or more subscripts.
33
2-D ARRAY
 A 2-D array, A with m X n elements.
 In math application it is called matrix.
 In business application – table.
 Example:
Assume 25 students had taken 4 tests.
The marks are stored in 25 X 4 array locations:
34
U0 U1 U2 U3
Stud 0 88 78 66 89
Stud 1 60 70 88 90
Stud 2 62 45 78 88
.. .. .. .. ..
.. .. .. .. ..
Stud 24 78 88 98 67
n
m
2-D ARRAY
 Multidimensional array declaration in C++:-
int StudentMarks [25][4];
StudentMarks[0][0] = 88;
StudentMarks[0][1] = 78;…..
OR
int StudentMarks [25][4] = {{88, 78, 66, 89},
{60, 70, 88, 90},…}
35
2.3.1 2-D ARRAY
 In C++ the 2-D array is visualized as follows:
36
…
[0]
[1]
[2]
[3]
[4]
[5]
[6]
[24]
StudentMarks
88 78 66 89
60 70 88 90
62 45 78 88
[0] [1] [2] [3]
2.3.2 Representation of
2D arrays in Memory
Column Major Order:
LOC(A[j, k])=Base(A)+w[m*k + j]
Row Major order:
LOC(A[j, k])=Base(A)+w[n*j + k]
Given: A 2-D array, A with m X n elements.
Thank You
38

More Related Content

What's hot (20)

Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
Adam Mukharil Bachtiar
 
Heaps
HeapsHeaps
Heaps
Hafiz Atif Amin
 
Linked lists a
Linked lists aLinked lists a
Linked lists a
Khuram Shahzad
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional array
Rajendran
 
Introduction to data structure ppt
Introduction to data structure pptIntroduction to data structure ppt
Introduction to data structure ppt
NalinNishant3
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structures
Mohd Arif
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
LGS, GBHS&IC, University Of South-Asia, TARA-Technologies
 
Graph traversals in Data Structures
Graph traversals in Data StructuresGraph traversals in Data Structures
Graph traversals in Data Structures
Anandhasilambarasan D
 
Arrays
ArraysArrays
Arrays
SARITHA REDDY
 
Bubble sort
Bubble sortBubble sort
Bubble sort
Manek Ar
 
Unit 3 daa
Unit 3 daaUnit 3 daa
Unit 3 daa
Nv Thejaswini
 
CLR AND LALR PARSER
CLR AND LALR PARSERCLR AND LALR PARSER
CLR AND LALR PARSER
Akila Krishnamoorthy
 
Array ppt
Array pptArray ppt
Array ppt
Kaushal Mehta
 
Linked List
Linked ListLinked List
Linked List
Ashim Lamichhane
 
Array
ArrayArray
Array
Anil Neupane
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
sagar yadav
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data Structure
Meghaj Mallick
 
Circular queue
Circular queueCircular queue
Circular queue
Lovely Professional University
 
Data Structure and Algorithms Linked List
Data Structure and Algorithms Linked ListData Structure and Algorithms Linked List
Data Structure and Algorithms Linked List
ManishPrajapati78
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Naz Abdalla
 

Similar to Data Structure and Algorithms Arrays (20)

ds 2Arrays.ppt
ds 2Arrays.pptds 2Arrays.ppt
ds 2Arrays.ppt
AlliVinay1
 
Array 2
Array 2Array 2
Array 2
Abbott
 
DS - Unit 2 FINAL (2).pptx
DS - Unit 2 FINAL (2).pptxDS - Unit 2 FINAL (2).pptx
DS - Unit 2 FINAL (2).pptx
prakashvs7
 
Data Structures_ Sorting & Searching
Data Structures_ Sorting & SearchingData Structures_ Sorting & Searching
Data Structures_ Sorting & Searching
ThenmozhiK5
 
Searching & Algorithms IN DATA STRUCTURES
Searching & Algorithms IN DATA STRUCTURESSearching & Algorithms IN DATA STRUCTURES
Searching & Algorithms IN DATA STRUCTURES
RAKSHITDOGRA1
 
data_structure_Chapter two_computer.pptx
data_structure_Chapter two_computer.pptxdata_structure_Chapter two_computer.pptx
data_structure_Chapter two_computer.pptx
Mohammed472103
 
arrays1.ppt python programme arrays insertion
arrays1.ppt python programme arrays insertionarrays1.ppt python programme arrays insertion
arrays1.ppt python programme arrays insertion
bushraashraf639
 
Unit 6 dsa SEARCHING AND SORTING
Unit 6 dsa SEARCHING AND SORTINGUnit 6 dsa SEARCHING AND SORTING
Unit 6 dsa SEARCHING AND SORTING
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
MODULE 5-Searching and-sorting
MODULE 5-Searching and-sortingMODULE 5-Searching and-sorting
MODULE 5-Searching and-sorting
nikshaikh786
 
Searching, Sorting and Hashing Techniques
Searching, Sorting and Hashing TechniquesSearching, Sorting and Hashing Techniques
Searching, Sorting and Hashing Techniques
Selvaraj Seerangan
 
Data structure Unit - II Searching and Sorting.pptx
Data structure Unit - II Searching and Sorting.pptxData structure Unit - II Searching and Sorting.pptx
Data structure Unit - II Searching and Sorting.pptx
gavanisanjana
 
Algorithm & data structures lec4&5
Algorithm & data structures lec4&5Algorithm & data structures lec4&5
Algorithm & data structures lec4&5
Abdul Khan
 
Searching and Sorting Algorithms in Data Structures
Searching and Sorting Algorithms  in Data StructuresSearching and Sorting Algorithms  in Data Structures
Searching and Sorting Algorithms in Data Structures
poongothai11
 
Module_1 Linear search search and Bsearch).pptx
Module_1 Linear search search and Bsearch).pptxModule_1 Linear search search and Bsearch).pptx
Module_1 Linear search search and Bsearch).pptx
vidhyapm2
 
Searching
SearchingSearching
Searching
Muhammad Farhan
 
PPS 5.5.BASIC ALGORITHMS SEARCHING (LINEAR SEARCH, BINARY SEARCH ETC.), BASI...
PPS 5.5.BASIC ALGORITHMS  SEARCHING (LINEAR SEARCH, BINARY SEARCH ETC.), BASI...PPS 5.5.BASIC ALGORITHMS  SEARCHING (LINEAR SEARCH, BINARY SEARCH ETC.), BASI...
PPS 5.5.BASIC ALGORITHMS SEARCHING (LINEAR SEARCH, BINARY SEARCH ETC.), BASI...
Sitamarhi Institute of Technology
 
Searching.ppt
Searching.pptSearching.ppt
Searching.ppt
SpammemeLmao
 
CHAP 3 ALGORITHM for infomatique ingenieure .ppt
CHAP 3 ALGORITHM for infomatique ingenieure .pptCHAP 3 ALGORITHM for infomatique ingenieure .ppt
CHAP 3 ALGORITHM for infomatique ingenieure .ppt
FarahHarrathi1
 
Lecture_Oct26.pptx
Lecture_Oct26.pptxLecture_Oct26.pptx
Lecture_Oct26.pptx
SylrizcinMarieManzo3
 
Data Structures Unit 2 FINAL presentation.pptx
Data Structures   Unit 2 FINAL presentation.pptxData Structures   Unit 2 FINAL presentation.pptx
Data Structures Unit 2 FINAL presentation.pptx
dilipd20
 
ds 2Arrays.ppt
ds 2Arrays.pptds 2Arrays.ppt
ds 2Arrays.ppt
AlliVinay1
 
Array 2
Array 2Array 2
Array 2
Abbott
 
DS - Unit 2 FINAL (2).pptx
DS - Unit 2 FINAL (2).pptxDS - Unit 2 FINAL (2).pptx
DS - Unit 2 FINAL (2).pptx
prakashvs7
 
Data Structures_ Sorting & Searching
Data Structures_ Sorting & SearchingData Structures_ Sorting & Searching
Data Structures_ Sorting & Searching
ThenmozhiK5
 
Searching & Algorithms IN DATA STRUCTURES
Searching & Algorithms IN DATA STRUCTURESSearching & Algorithms IN DATA STRUCTURES
Searching & Algorithms IN DATA STRUCTURES
RAKSHITDOGRA1
 
data_structure_Chapter two_computer.pptx
data_structure_Chapter two_computer.pptxdata_structure_Chapter two_computer.pptx
data_structure_Chapter two_computer.pptx
Mohammed472103
 
arrays1.ppt python programme arrays insertion
arrays1.ppt python programme arrays insertionarrays1.ppt python programme arrays insertion
arrays1.ppt python programme arrays insertion
bushraashraf639
 
MODULE 5-Searching and-sorting
MODULE 5-Searching and-sortingMODULE 5-Searching and-sorting
MODULE 5-Searching and-sorting
nikshaikh786
 
Searching, Sorting and Hashing Techniques
Searching, Sorting and Hashing TechniquesSearching, Sorting and Hashing Techniques
Searching, Sorting and Hashing Techniques
Selvaraj Seerangan
 
Data structure Unit - II Searching and Sorting.pptx
Data structure Unit - II Searching and Sorting.pptxData structure Unit - II Searching and Sorting.pptx
Data structure Unit - II Searching and Sorting.pptx
gavanisanjana
 
Algorithm & data structures lec4&5
Algorithm & data structures lec4&5Algorithm & data structures lec4&5
Algorithm & data structures lec4&5
Abdul Khan
 
Searching and Sorting Algorithms in Data Structures
Searching and Sorting Algorithms  in Data StructuresSearching and Sorting Algorithms  in Data Structures
Searching and Sorting Algorithms in Data Structures
poongothai11
 
Module_1 Linear search search and Bsearch).pptx
Module_1 Linear search search and Bsearch).pptxModule_1 Linear search search and Bsearch).pptx
Module_1 Linear search search and Bsearch).pptx
vidhyapm2
 
PPS 5.5.BASIC ALGORITHMS SEARCHING (LINEAR SEARCH, BINARY SEARCH ETC.), BASI...
PPS 5.5.BASIC ALGORITHMS  SEARCHING (LINEAR SEARCH, BINARY SEARCH ETC.), BASI...PPS 5.5.BASIC ALGORITHMS  SEARCHING (LINEAR SEARCH, BINARY SEARCH ETC.), BASI...
PPS 5.5.BASIC ALGORITHMS SEARCHING (LINEAR SEARCH, BINARY SEARCH ETC.), BASI...
Sitamarhi Institute of Technology
 
CHAP 3 ALGORITHM for infomatique ingenieure .ppt
CHAP 3 ALGORITHM for infomatique ingenieure .pptCHAP 3 ALGORITHM for infomatique ingenieure .ppt
CHAP 3 ALGORITHM for infomatique ingenieure .ppt
FarahHarrathi1
 
Data Structures Unit 2 FINAL presentation.pptx
Data Structures   Unit 2 FINAL presentation.pptxData Structures   Unit 2 FINAL presentation.pptx
Data Structures Unit 2 FINAL presentation.pptx
dilipd20
 
Ad

More from ManishPrajapati78 (14)

Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeData Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search Tree
ManishPrajapati78
 
Data Structure and Algorithms Binary Tree
Data Structure and Algorithms Binary TreeData Structure and Algorithms Binary Tree
Data Structure and Algorithms Binary Tree
ManishPrajapati78
 
Data Structure and Algorithms Queues
Data Structure and Algorithms QueuesData Structure and Algorithms Queues
Data Structure and Algorithms Queues
ManishPrajapati78
 
Data Structure and Algorithms Merge Sort
Data Structure and Algorithms Merge SortData Structure and Algorithms Merge Sort
Data Structure and Algorithms Merge Sort
ManishPrajapati78
 
Data Structure and Algorithms The Tower of Hanoi
Data Structure and Algorithms The Tower of HanoiData Structure and Algorithms The Tower of Hanoi
Data Structure and Algorithms The Tower of Hanoi
ManishPrajapati78
 
Data Structure and Algorithms Stacks
Data Structure and Algorithms StacksData Structure and Algorithms Stacks
Data Structure and Algorithms Stacks
ManishPrajapati78
 
Data Structure and Algorithms Sorting
Data Structure and Algorithms SortingData Structure and Algorithms Sorting
Data Structure and Algorithms Sorting
ManishPrajapati78
 
Data Structure and Algorithms
Data Structure and Algorithms Data Structure and Algorithms
Data Structure and Algorithms
ManishPrajapati78
 
Data Structure and Algorithms Hashing
Data Structure and Algorithms HashingData Structure and Algorithms Hashing
Data Structure and Algorithms Hashing
ManishPrajapati78
 
Data Structure and Algorithms Graph Traversal
Data Structure and Algorithms Graph TraversalData Structure and Algorithms Graph Traversal
Data Structure and Algorithms Graph Traversal
ManishPrajapati78
 
Data Structure and Algorithms Graphs
Data Structure and Algorithms GraphsData Structure and Algorithms Graphs
Data Structure and Algorithms Graphs
ManishPrajapati78
 
Data Structure and Algorithms Huffman Coding Algorithm
Data Structure and Algorithms Huffman Coding AlgorithmData Structure and Algorithms Huffman Coding Algorithm
Data Structure and Algorithms Huffman Coding Algorithm
ManishPrajapati78
 
Data Structure and Algorithms Heaps and Trees
Data Structure and Algorithms Heaps and TreesData Structure and Algorithms Heaps and Trees
Data Structure and Algorithms Heaps and Trees
ManishPrajapati78
 
Data Structure and Algorithms AVL Trees
Data Structure and Algorithms AVL TreesData Structure and Algorithms AVL Trees
Data Structure and Algorithms AVL Trees
ManishPrajapati78
 
Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeData Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search Tree
ManishPrajapati78
 
Data Structure and Algorithms Binary Tree
Data Structure and Algorithms Binary TreeData Structure and Algorithms Binary Tree
Data Structure and Algorithms Binary Tree
ManishPrajapati78
 
Data Structure and Algorithms Queues
Data Structure and Algorithms QueuesData Structure and Algorithms Queues
Data Structure and Algorithms Queues
ManishPrajapati78
 
Data Structure and Algorithms Merge Sort
Data Structure and Algorithms Merge SortData Structure and Algorithms Merge Sort
Data Structure and Algorithms Merge Sort
ManishPrajapati78
 
Data Structure and Algorithms The Tower of Hanoi
Data Structure and Algorithms The Tower of HanoiData Structure and Algorithms The Tower of Hanoi
Data Structure and Algorithms The Tower of Hanoi
ManishPrajapati78
 
Data Structure and Algorithms Stacks
Data Structure and Algorithms StacksData Structure and Algorithms Stacks
Data Structure and Algorithms Stacks
ManishPrajapati78
 
Data Structure and Algorithms Sorting
Data Structure and Algorithms SortingData Structure and Algorithms Sorting
Data Structure and Algorithms Sorting
ManishPrajapati78
 
Data Structure and Algorithms
Data Structure and Algorithms Data Structure and Algorithms
Data Structure and Algorithms
ManishPrajapati78
 
Data Structure and Algorithms Hashing
Data Structure and Algorithms HashingData Structure and Algorithms Hashing
Data Structure and Algorithms Hashing
ManishPrajapati78
 
Data Structure and Algorithms Graph Traversal
Data Structure and Algorithms Graph TraversalData Structure and Algorithms Graph Traversal
Data Structure and Algorithms Graph Traversal
ManishPrajapati78
 
Data Structure and Algorithms Graphs
Data Structure and Algorithms GraphsData Structure and Algorithms Graphs
Data Structure and Algorithms Graphs
ManishPrajapati78
 
Data Structure and Algorithms Huffman Coding Algorithm
Data Structure and Algorithms Huffman Coding AlgorithmData Structure and Algorithms Huffman Coding Algorithm
Data Structure and Algorithms Huffman Coding Algorithm
ManishPrajapati78
 
Data Structure and Algorithms Heaps and Trees
Data Structure and Algorithms Heaps and TreesData Structure and Algorithms Heaps and Trees
Data Structure and Algorithms Heaps and Trees
ManishPrajapati78
 
Data Structure and Algorithms AVL Trees
Data Structure and Algorithms AVL TreesData Structure and Algorithms AVL Trees
Data Structure and Algorithms AVL Trees
ManishPrajapati78
 
Ad

Recently uploaded (20)

Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native BarcelonaOpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
Insurance Tech Services
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
Leveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer IntentsLeveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer Intents
Keheliya Gallaba
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Software Testing & it’s types (DevOps)
Software  Testing & it’s  types (DevOps)Software  Testing & it’s  types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native BarcelonaOpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
Insurance Tech Services
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
Leveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer IntentsLeveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer Intents
Keheliya Gallaba
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Software Testing & it’s types (DevOps)
Software  Testing & it’s  types (DevOps)Software  Testing & it’s  types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 

Data Structure and Algorithms Arrays

  • 1.  Linear arrays: Memory representation  Traversal  Insertion  Deletion  Linear Search  Binary Search  Merging  2D Array : Memory representation 1
  • 2. CONTENTS 2.1 Introductions 2.2 Linear Array 2.2.1 Linear Array Representations in Memory 2.2.2 Traversing Algorithm 2.2.3 Insert Algorithms 2.2.4 Delete Algorithms 2.2.5 Sequential and Binary Search Algorithm 2.2.6 Merging Algorithm 2.3 Multidimensional Array 2.3.1 2-D Array 2.3.2 Representations in Memory 2
  • 3. 2.1 Introduction Data Structure can be classified as: linear non-linear Linear (elements arranged in sequential in memory location) i.e. array & linear link-list Non-linear such as a tree and graph. Operations: Traversing, Searching, Inserting, Deleting, Sorting, Merging Array is used to store a fix size for data and a link-list the data can be varies in size. 3
  • 4. 2.1 Introduction Advantages of an Array: Very simple Economy – if full use of memory Random accessed at the same time Disadvantage of an Array: wasting memory if not fully used 4
  • 5. 2.2 Linear Array  Homogeneous data: a) Elements are represented through indexes. b) Elements are saved in sequential in memory locations.  Number of elements, N –> length or size of an array. If: UB : upper bound ( the largest index) LB : lower bound (the smallest index) Then: N = UB – LB + 1 Length = N = UB when LB = 1 5
  • 6. 2.2 Linear Array  All elements in A are written symbolically as, 1 .. n is the subscript. A1, A2, A3, .... , An  In FORTRAN and BASIC  A(1), A(2), ..., A(N)  In Pascal, C/C++ and Java  A[0], A[1], ..., A[N-1]  subscript starts from 0 LB = 0, UB = N–1 6
  • 7. 2.2.1 Representation of Array in a Memory  The process to determine the address in a memory: a) First address – base address. b) Relative address to base address through index function. Example: char X[100]; Let char uses 1 location storage. If the base address is 1200 then the next element is in 1201. Index Function is written as: Loc (X[i]) = Loc(X[0]) + i , i is subscript and LB = 0 1200 1201 1202 1203 X[0] X[1] X[2] 7
  • 8. 2.2.1 Representation of Array in a Memory  In general, index function: Loc (X[i]) = Loc(X[LB]) + w*(i-LB); where w is length of memory location required. For real number: 4 byte, integer: 2 byte and character: 1 byte.  Example: If LB = 5, Loc(X[LB]) = 1200, and w = 4, find Loc(X[8]) ? Loc(X[8])= Loc(X[5]) + 4*(8 – 5) = 1212 8
  • 9. 2.2.2 Traversing Algorithm  Traversing operation means visit every element once. e.g. to print, etc.  Example algorithm: 9 1. [Assign counter] K=LB // LB = 0 2. Repeat step 2.1 and 2.2 while K <= UB // If LB = 0 2.1 [visit element] do PROCESS on LA[K] 2.2 [add counter] K=K+1 3. end repeat step 2 4. exit
  • 10. 2.2.3 Insertion Algorithm  Insert item at the back is easy if there is a space. Insert item in the middle requires the movement of all elements to the right as in Figure 1. 0 1 2 3 4 k MAX_LIST-1 1 2 3 4 5 k+1 MAX_LIST 10 12 3 44 19 100 … 5 10 18 ? … ? k+1 size Array indexes New item ADT list positions items Figure 1: Shifting items for insertion at position 3
  • 11. 2.2.3 Insertion Algorithm  Example algorithm: 11 INSERT(LA, N, K, ITEM) //LA is a linear array with N element //K is integer positive where K < N and LB = 0 //Insert an element, ITEM in index K 1. [Assign counter] J = N – 1; // LB = 0 2. Repeat step 2.1 and 2.2 while J >= K 2.1 [shift to the right all elements from J] LA[J+1] = LA[J] 2.2 [decrement counter] J = J – 1 3. [Stop repeat step 2] 4. [Insert element] LA[K] = ITEM 5. [Reset N] N = N + 1 6. Exit
  • 12. 2.2.4 Deletion Algorithm  Delete item. (a) 0 1 2 3 4 k-1 k MAX_LIST-1 1 2 3 4 5 k k+1 MAX_LIST 12 12 3 44 100 … 5 10 18 ? … ? k size Array indexes Delete 19 ADT list positions items Figure 2: Deletion causes a gap
  • 13. 2.2.4 Deletion Algorithm (b) 0 1 2 3 k-1 MAX_LIST-1 1 2 3 4 k MAX_LIST 13 12 3 44 100 … 5 10 18 ? … ? k size Array indexes ADT list positions items Figure 3: Fill gap by shifting
  • 14. 2.2.4 Deletion Algorithm  Example algorithm: 14 DELETE(LA, N, K, ITEM) 1. ITEM = LA[K] 2. Repeat for I = K to N–2 // If LB = 0 2.1 [Shift element, forward] LA[I] = LA[I+1] 3. [end of loop] 4. [Reset N in LA] N = N – 1 5. Exit
  • 15. 2.2.5 Sequential Search Compare successive elements of a given list with a search ITEM until 1. either a match is encountered 2. or the list is exhausted without a match. 0 1 N-1 Algorithm: SequentialSearch(LA, N, ITEM, LOC) 1. I = 0 // If LB = 0 2. Repeat step 2.1 while (i<N and LA[I] != ITEM ) 2.1 I=I+1 3. If LA[I]==ITEM then Return found at LOC=I If not Return not found 15
  • 16. 2.2.5 Binary Search Algorithm  Binary search algorithm is efficient if the array is sorted.  A binary search is used whenever the list starts to become large.  Consider to use binary searches whenever the list contains more than 16 elements.  The binary search starts by testing the data in the element at the middle of the array to determine if the target is in the first or second half of the list.  If it is in the first half, we do not need to check the second half. If it is in the second half, we do not need to test the first half. In other words we eliminate half the list from further consideration. We repeat this process until we find the target or determine that it is not in the list. 16
  • 17. 2.2.5 Binary Search Algorithm  To find the middle of the list, we need three variables, one to identify the beginning of the list, one to identify the middle of the list, and one to identify the end of the list.  We analyze two cases here: the target is in the list (target found) and the target is not in the list (target not found). 17
  • 18. 2.2.5 Binary Search Algorithm  Target found case: Assume we want to find 22 in a sorted list as follows:  The three indexes are first, mid and last. Given first as 0 and last as 11, mid is calculated as follows: mid = (first + last) / 2 mid = (0 + 11) / 2 = 11 / 2 = 5 18 4 7 8 10 14 21 22 36 62 77 81 91 a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[10] a[11]
  • 19. 2.2.5 Binary Search Algorithm  At index location 5, the target is greater than the list value (22 > 21). Therefore, eliminate the array locations 0 through 5 (mid is automatically eliminated). To narrow our search, we assign mid + 1 to first and repeat the search. 19 4 7 8 10 14 21 22 36 62 77 81 91 a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[10] a[11] 0 5 11 first mid last Target: 22Target: 22 22 > 21
  • 20. 2.2.5 Binary Search Algorithm  The next loop calculates mid with the new value for first and determines that the midpoint is now 8 as follows: mid = (6 + 11) / 2 = 17 / 2 = 8 20 4 7 8 10 14 21 22 36 62 77 81 91 a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[10] a[11] 6 8 11 first mid last Target: 22Target: 22 22 < 62
  • 21. 2.2.5 Binary Search Algorithm  When we test the target to the value at mid a second time, we discover that the target is less than the list value (22 < 62). This time we adjust the end of the list by setting last to mid – 1 and recalculate mid. This step effectively eliminates elements 8 through 11 from consideration. We have now arrived at index location 6, whose value matches our target. This stops the search. 21 4 7 8 10 14 21 22 36 62 77 81 91 a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[10] a[11] 6 6 7 first mid last Target: 22Target: 22 22 equals 228 6 7 function terminates first mid last
  • 22. 2.2.5 Binary Search Algorithm  Target not found case: This is done by testing for first and last crossing: that is, we are done when first becomes greater than last. Two conditions terminate the binary search algorithm when (a) the target is found or (b) first becomes larger than last. Assume we want to find 11 in our binary search array. 22 4 7 8 10 14 21 22 36 62 77 81 91 a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[10] a[11] 0 5 11 first mid last Target: 11Target: 11 11 < 21
  • 23. 2.2.5 Binary Search Algorithm  The loop continues to narrow the range as we saw in the successful search until we are examining the data at index locations 3 and 4. 23 4 7 8 10 14 21 22 36 62 77 81 91 a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[10] a[11] 0 2 4 first mid last Target: 11Target: 11 11 > 8
  • 24. 2.2.5 Binary Search Algorithm  These settings of first and last set the mid index to 3 as follows: mid = (3 + 4) / 2 = 7 / 2 = 3 24 4 7 8 10 14 21 22 36 62 77 81 91 a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[10] a[11] 3 3 4 first mid last Target: 11Target: 11 11 > 10
  • 25. 2.2.5 Binary Search Algorithm  The test at index 3indicates that the target is greater than the list value, so we set first to mid + 1, or 4. We now test the data at location 4 and discover that 11 < 14. The mid is as calculated as follows:  At this point, we have discovered that the target should be between two adjacent values; in other words, it is not in the list. We see this algorithmically because last is set to mid – 1, which makes first greater than last, the signal that the value we are looking for is not in the list. 25 4 7 8 10 14 21 22 36 62 77 81 91 a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[10] a[11] 4 4 4 first mid last Target: 11Target: 11 11 < 14 4 4 3 first mid last Function terminates
  • 26. 2.2.5 Binary Search Algorithm  Example algorithm: DATA – sorted array ITEM – Info LB – lower bound UB – upper bound ST – start Location MID – middle Location LAST – last Location 26
  • 27. 2.2.5 Binary Search Algorithm 27 1. [Define variables] ST = LB, LAST= UB; MID = (ST+LAST)/2; 2. Repeat 3 and 4 WHILE (ST <= LAST & DATA[MID] != ITEM) 3. If ITEM < DATA[MID] then LAST = MID-1 If not ST = MID+1 4. Set MID = INT((ST + LAST)/2) [LAST repeat to 2] 5. If DATA[MID] == ITEM then LOK = MID If not LOK = NULL 6. Stop
  • 28. 2.2.6 Merging Algorithm Suppose A is a sorted list with r elements and B is a sorted list with s elements. The operation that combines the element of A and B into a single sorted list C with n=r + s elements is called merging. 28
  • 29. 2.2.6 Merging Algorithm Algorithm: Merging (A, R,B,S,C) Here A and B be sorted arrays with R and S elements respectively. This algorithm merges A and B into an array C with N=R+ S elements Step 1: Set NA=1, NB=1 and NC=1 Step 2: Repeat while NA ≤ R and NB ≤ S: if A[NA] ≤ B[NB], then: Set C[NC] = A[NA] Set NA = NA +1 else Set C[NC] = B[NB] Set NB = NB +1 [End of if structure] Set NC= NC +1 [End of Loop] 29
  • 30. 2.2.6 Merging Algorithm Step 3: If NA >R, then: Repeat while NB ≤ S: Set C[NC] = B[NB] Set NB = NB+1 Set NC = NC +1 [End of Loop] else Repeat while NA ≤ R: Set C[NC] = A[NA] Set NC = NC + 1 Set NA = NA +1 [End of loop] [End of if structure] Step 4: Return C[NC] 30
  • 31. 2.2.6 Merging Algorithm Complexity of merging: The input consists of the total number n=r+s elements in A and B. Each comparison assigns an element to the array C, which eventually has n elements. Accordingly, the number f(n) of comparisons cannot exceed n: f(n) ≤ n = O(n) 31
  • 32. Exercises Find where the indicated elements of an array a are stored, if the base address of a is 200* and LB = 0 a) double a[10]; a[3]? b) int a[26]; a[2]? *(assume that int(s) are stored in 4 bytes and double(s) in 8 bytes). 32
  • 33. 2.3 MULTIDIMENSIONAL ARRAY  Two or more subscripts. 33
  • 34. 2-D ARRAY  A 2-D array, A with m X n elements.  In math application it is called matrix.  In business application – table.  Example: Assume 25 students had taken 4 tests. The marks are stored in 25 X 4 array locations: 34 U0 U1 U2 U3 Stud 0 88 78 66 89 Stud 1 60 70 88 90 Stud 2 62 45 78 88 .. .. .. .. .. .. .. .. .. .. Stud 24 78 88 98 67 n m
  • 35. 2-D ARRAY  Multidimensional array declaration in C++:- int StudentMarks [25][4]; StudentMarks[0][0] = 88; StudentMarks[0][1] = 78;….. OR int StudentMarks [25][4] = {{88, 78, 66, 89}, {60, 70, 88, 90},…} 35
  • 36. 2.3.1 2-D ARRAY  In C++ the 2-D array is visualized as follows: 36 … [0] [1] [2] [3] [4] [5] [6] [24] StudentMarks 88 78 66 89 60 70 88 90 62 45 78 88 [0] [1] [2] [3]
  • 37. 2.3.2 Representation of 2D arrays in Memory Column Major Order: LOC(A[j, k])=Base(A)+w[m*k + j] Row Major order: LOC(A[j, k])=Base(A)+w[n*j + k] Given: A 2-D array, A with m X n elements.