SlideShare a Scribd company logo
1 of 34
CS261
DATA STRUCTURES & ALGORITHMS
(WEEK-8)
LECTURE-15 & 16
INTRODUCTION TO DATA STRUCTURES &
ALGORITHMS
Lecturer
Azka Aziz
Azka.a@scocs.edu.pk
Data structures & Algorithms
Lecture#15 Merge Sort
Lecture Contents
Divide & Conquer
Divide & Conquer ….. Application (Merge Sort)
mergeSort()
Merge()
Analysis
Divide & Conquer
Idea
Distribute a larger problem into many small similar problems
Solve every smaller problem recursively
Combine results of smaller solutions to form the overall solution
Usage
A typical idea be to split a list of n items into two lists of n/2 size and try
to sort them
Consequence
Running time of sorting can be improved from O(n2) to O(n log n)
Divide & Conquer ….. Application (Merge
Sort)
Divide and conquer strategy is applicable in a huge number of computational
problems.
The first application of divide and conquer strategy is a simple and efficient
sorting procedure called Merge Sort
Input: a list of n numbers is provided as an array A[1…n]
Output: a permutation of this sequence sorted in increasing order
Method: Split Recursively, Sort, Merge
Merge Sort Algorithm
proc mergeSort(arr[1…n], p, r)
if p < r then
q  (p+r)/2
mergeSort(arr, p, q)
mergeSort(arr, q+1, r)
merge(arr, p, q, r)
end if
end proc
Every pass of mergeSort()
procedure consists of two
recursive function calls followed by
one call to merge
Merge Sort Algorithm
proc mergeSort(arr[1…n], p, r)
if p < r then
q  (p+r)/2
mergeSort(arr, p, q)
mergeSort(arr, q+1, r)
merge(arr, p, q, r)
end if
end proc
mergeSort(arr, p, r) function checks
whether p (index) is less than r (index)
If it is so, it makes two calls to itself
splitting the array into two halves
Every further call splits array into further
two halves with available indexes until p is
not less than r (when will this happen?)
Merge Sort Algorithm
proc mergeSort(arr[1…n], p, r)
if p < r then
q  (p+r)/2
mergeSort(arr, p, q)
mergeSort(arr, q+1, r)
merge(arr, p, q, r)
end if
end proc
Every further call splits array into further
two halves with available indexes until p is
not less than r (when will this happen?)
At this point a merge(arr, p, q, r) call will
me made to merge two halves into a
sorted chunk
mergeSort() calls … Visually
merge() call
merge(arr, p, q, r) assumes that two halves of array [p….q], [q+1….r]
are sorted (Why is it? We have not sorted anything yet? Is there
some statement in mergeSort() procedure that does the sorting
part?)
proc mergeSort(arr[1…n], p, r)
if p < r then
q  (p+r)/2
mergeSort(arr, p, q)
mergeSort(arr, q+1, r)
merge(arr, p, q, r)
end if
end proc
mergeSort() calls … Visually
We have not sorted
anything yet?
Is there some
statement in
mergeSort()
procedure that does
the sorting part?
We just relied on a simple fact that splitting an array
into equal halves will result into smaller and smaller
arrays till there is only one element in array
Is single element array sorted? Always?
merge(arr, p, q, r) calls …
Every merge() call receives three parameters (except the data
array) i.e. p, q, r
Values between indexes p….q and q+1……r are sorted
(independent of each other)
Having two sorted sub-arrays, merging part is easier:::
merge(arr, p, q, r) calls …
proc merge(arr, p, q, r)
ip, kp, jq+1
temp[p…r] // using a temporary array
while i ≤ q and j ≤ r do
if arr[i] < arr[j] then
temp[k++]  arr[i++]
else
temp[k++]  arr[j++]
end if
next
merge(arr, p, q, r) calls … continued
while i ≤ q do
temp[k++]  arr[i++]
next
while j ≤ r do
temp[k++]  arr[j++]
next
for i p to r do
arr[i]  temp[i]
next
end proc
merge() calls … Visually
Merge Sort Analysis
First we analyze merge() procedure
First let us consider the running
time of the procedure merge(A, p, q,
r). Let n = r - p + 1 denote the total
length of both the left and right sub-
arrays. What is the running time of
Merge as a function of n?
Merge Sort Analysis
Cost of mergeSort(with n elements) = cost of mergeSort(n/2 elements)
+ cost of mergeSort(n/2 elements) + cost of merge(n elements)
MS(n) = MS(n/2) + MS(n/2)+M(n)
MS(n) = 2MS(n/2) + M(n)
Merge Sort Analysis
T(1) = 1
T(2) = T(1) + T(1) + 2 = 1 + 1 + 2 = 4
T(3) = T(2) + T(1) + 3 = 4 + 1 + 3 = 8
T(4) = T(2) + T(2) + 4 = 8 + 8 + 4 = 12
T(5) = T(3) + T(2) + 5 = 8 + 4 + 5 = 17
. . .
T(8) = T(4) + T(4) + 8 = 12 + 12 + 8 = 32
. . .
T(16) = T(8) + T(8) + 16 = 32 + 32 + 16 =
80
T(32) = T(16) + T(16) + 32 = 80 + 80+ 32
= 192
Merge Sort Analysis T(1) = 1
T(2) = T(1) + T(1) + 2 = 1 + 1 + 2 = 4
T(3) = T(2) + T(1) + 3 = 4 + 1 + 3 = 8
T(4) = T(2) + T(2) + 4 = 8 + 8 + 4 = 12
T(5) = T(3) + T(2) + 5 = 8 + 4 + 5 = 17
. . .
T(8) = T(4) + T(4) + 8 = 12 + 12 + 8 = 32
. . .
T(16) = T(8) + T(8) + 16 = 32 + 32 + 16 =
80
T(32) = T(16) + T(16) + 32 = 80 + 80+ 32
= 192
Is there some pattern?
Let’s try
T(n)/n = log n + 1
T(n) = n log n + n
O(n log n)
Merge Sort Analysis … Recurrence Relation
T(n) = 2 T(n/2) + n
Expanding we get
T(n) = 2 (2T(n/4)+n/2)+n ….. ? How?
= 4 T(n/4) + n + n
= 8 T(n/8) + n + n + n
= 16 T(n/16) + n + n + n + n
= …………….
Now to solve it assuming that n = 2k,
T(n) = 2k T(n/2k) + (n+n+n+n k items)
T(n) = 2k T(n/2k) + kn
Merge Sort Analysis … Recurrence Relation
T(n) = 2 T(n/2) + n
Expanding we get
T(n) = 2 (2T(n/4)+n/2)+n
= 4 T(n/4) + n + n
= 8 T(n/8) + n + n + n
= 16 T(n/16) + n + n +
n + n
= …………….
Now to solve it assuming that n =
2k,
T(n) = 2k T(n/2k) + (n+n+n+n k
Since n = 2k, i.e. k = log n
T(n) = 2log n T(n/2log n) + (log n)n
T(n) = n T(1) + n log n
T(n) = n + n log n
i.e. T(n) = O (n)
Merge Sort Analysis … Recurrence Relation
Data structures & Algorithms
Lecture#16 Queue
Queue Data Structure
Queue is a data structure that is used to store data items.
Data items are stored in Queue one by one. Stored data
items when removed from Queue follow First In First Out
order.
Queue
Queue maintains two control variables i. rear ii. front
Data items are removed from Queue (deque() operation) using control
variable ‘rear’
Data items are added to the Queue (enque() operation) using control
variable ‘front’
Data item being enqued to Queue earliest will be removed from Queue
earliest following First In First Out order (FIFO)
Queue can be implemented using an Array as well as a Linked List
Queue Operations …
Operation Description Pseudocode
Queue() Initialize ‘rear’ and ‘front’
with -1
 Assign -1 to ‘rear’
 Assign -1 to ‘front’
int is_empty() Returns TRUE if Queue is
empty
Returns FALSE if Queue is
not empty
 If ‘rear’ is less than ‘front’
 Return FALSE
 Otherwise
 Return TRUE
int is_full() Returns TRUE if Queue is
empty
Returns FALSE if Queue is
not empty
 If ‘rear’ is equal to -1 AND ‘front’ is equal to MAX-1
then
 Return TRUE
 Otherwise
 Return FALSE
Queue Operations …
Operation Description Pseudocode
int deque() Removes one item from
queue using ‘rear’
 If Queue is empty
 It returns -1
 Otherwise
 Increment ‘rear’ by 1
 Return value at current location of ‘rear’
void refresh() Relocates the queue
elements so that empty
positions are available post
‘front’ pointer
 All elements are relocated to the smaller index
positions making empty positions available post the
‘front’ locations
 Assign -1 to ‘rear’ and value of (‘front’-’rear’-1) to
‘front’
void enque() Added an new data item to
the Queue using ‘front’
pointer
 If Queue is full, Nothing can be added
 Else if ‘front’ is equal to MAX-1 then
 Refresh is called, ‘front’ is incremented by 1,
New element is added at ‘front’ location
 Otherwise
 ‘front’ is incremented by 1, New element is
added at ‘front’ location
Queue using array … implementation
Implementation details and issues have been discussed during
class
Queue ADT … (implementing with linked list)
Queue ADT … (implementing with linked list)
QueueNode *Front;
QueueNode *Rear;
Queue();
int is_empty();
void enque(int);
QueueNode* deque();
Queue Operations …
Operation Description Pseudocode
Queue() Initialize ‘rear’ and ‘front’ with
NULL
 Assign NULL to ‘rear’
 Assign NULL to ‘front’
int is_empty() Returns TRUE if Queue is
empty
Returns FALSE if Queue is not
empty
 If ‘front’ is equal to NULL
 Return TRUE
 Otherwise
 Return FALSE
QueueNode* deque() Removes one item from queue
using ‘rear’
 If Queue is empty
 It returns NULL
 Else if ‘rear’ and ‘front’ point to same node
 Assign the node to QueueNode pointer ‘temp’
 Assign NULL to ‘rear’ and ‘front’
 Return ‘temp’
 Else
 Assign QueueNode pointed by ‘rear’ to ‘temp’
 Assign ‘prev’ of ‘rear’ to ‘rear’
 Set NULL to ‘next’ of ‘rear’
 Return ‘temp’
Queue Operations …
Operation Description Pseudocode
void enque(int) Added an new data item to
the Queue using ‘front’
pointer
 Create new node using the parameter of
function and point it by ‘temp’
 If Queue is empty
 Assign ‘temp’ to ‘front’
 Assign ‘temp’ to ‘rear’
 Else
 Assign ‘front’ to ‘next’ of ‘temp’
 Assign ‘temp’ to ‘prev’ of ‘front’
 Assign ‘temp’ to ‘front’
Queue using array … implementation
Implementation details and issues have been discussed during
class
Queue applications
Level order tree traversal
Any job management software following FIFO order
Operating System maintains a queue of processes that are ready to
execute
Many computer based systems maintains a queue of messages to be
communicated among their components
Queue of people at any service point
Queue of packets in data communication
Queue of planes waiting for landing

More Related Content

Similar to CS261 Data Structures & Algorithms (Week-8) Lectures on Merge Sort and Queue

Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0BG Java EE Course
 
19. algorithms and-complexity
19. algorithms and-complexity19. algorithms and-complexity
19. algorithms and-complexityshowkat27
 
Cs6402 design and analysis of algorithms may june 2016 answer key
Cs6402 design and analysis of algorithms may june 2016 answer keyCs6402 design and analysis of algorithms may june 2016 answer key
Cs6402 design and analysis of algorithms may june 2016 answer keyappasami
 
CSE680-07QuickSort.pptx
CSE680-07QuickSort.pptxCSE680-07QuickSort.pptx
CSE680-07QuickSort.pptxDeepakM509554
 
Bubble and-merge-sort
Bubble and-merge-sortBubble and-merge-sort
Bubble and-merge-sortnikhilsh66131
 
Dsa – data structure and algorithms sorting
Dsa – data structure and algorithms  sortingDsa – data structure and algorithms  sorting
Dsa – data structure and algorithms sortingsajinis3
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1smruti sarangi
 
Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"Ra'Fat Al-Msie'deen
 
time_complexity_list_02_04_2024_22_pages.pdf
time_complexity_list_02_04_2024_22_pages.pdftime_complexity_list_02_04_2024_22_pages.pdf
time_complexity_list_02_04_2024_22_pages.pdfSrinivasaReddyPolamR
 
T2311 - Ch 4_Part1.pptx
T2311 - Ch 4_Part1.pptxT2311 - Ch 4_Part1.pptx
T2311 - Ch 4_Part1.pptxGadaFarhan
 

Similar to CS261 Data Structures & Algorithms (Week-8) Lectures on Merge Sort and Queue (20)

Lec22
Lec22Lec22
Lec22
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
 
Unit 7 sorting
Unit 7   sortingUnit 7   sorting
Unit 7 sorting
 
Unit6 C
Unit6 C Unit6 C
Unit6 C
 
19. algorithms and-complexity
19. algorithms and-complexity19. algorithms and-complexity
19. algorithms and-complexity
 
Cs6402 design and analysis of algorithms may june 2016 answer key
Cs6402 design and analysis of algorithms may june 2016 answer keyCs6402 design and analysis of algorithms may june 2016 answer key
Cs6402 design and analysis of algorithms may june 2016 answer key
 
CSE680-07QuickSort.pptx
CSE680-07QuickSort.pptxCSE680-07QuickSort.pptx
CSE680-07QuickSort.pptx
 
Sorting
SortingSorting
Sorting
 
Ada notes
Ada notesAda notes
Ada notes
 
Bubble and-merge-sort
Bubble and-merge-sortBubble and-merge-sort
Bubble and-merge-sort
 
Dsa – data structure and algorithms sorting
Dsa – data structure and algorithms  sortingDsa – data structure and algorithms  sorting
Dsa – data structure and algorithms sorting
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1
 
Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"
 
time_complexity_list_02_04_2024_22_pages.pdf
time_complexity_list_02_04_2024_22_pages.pdftime_complexity_list_02_04_2024_22_pages.pdf
time_complexity_list_02_04_2024_22_pages.pdf
 
Mergesort
MergesortMergesort
Mergesort
 
Chap05alg
Chap05algChap05alg
Chap05alg
 
Chap05alg
Chap05algChap05alg
Chap05alg
 
Lec3
Lec3Lec3
Lec3
 
T2311 - Ch 4_Part1.pptx
T2311 - Ch 4_Part1.pptxT2311 - Ch 4_Part1.pptx
T2311 - Ch 4_Part1.pptx
 
Alg1
Alg1Alg1
Alg1
 

More from SajalFayyaz

Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptxSajalFayyaz
 
Data structure.ppt
Data structure.pptData structure.ppt
Data structure.pptSajalFayyaz
 
data structure 9.pptx
data structure 9.pptxdata structure 9.pptx
data structure 9.pptxSajalFayyaz
 
Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptxSajalFayyaz
 
Data structure 6.pptx
Data structure 6.pptxData structure 6.pptx
Data structure 6.pptxSajalFayyaz
 
Data Structure.pptx
Data Structure.pptxData Structure.pptx
Data Structure.pptxSajalFayyaz
 
Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptxSajalFayyaz
 
data structure3.pptx
data structure3.pptxdata structure3.pptx
data structure3.pptxSajalFayyaz
 
Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptxSajalFayyaz
 
Data Structure.pptx
Data Structure.pptxData Structure.pptx
Data Structure.pptxSajalFayyaz
 

More from SajalFayyaz (10)

Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptx
 
Data structure.ppt
Data structure.pptData structure.ppt
Data structure.ppt
 
data structure 9.pptx
data structure 9.pptxdata structure 9.pptx
data structure 9.pptx
 
Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptx
 
Data structure 6.pptx
Data structure 6.pptxData structure 6.pptx
Data structure 6.pptx
 
Data Structure.pptx
Data Structure.pptxData Structure.pptx
Data Structure.pptx
 
Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptx
 
data structure3.pptx
data structure3.pptxdata structure3.pptx
data structure3.pptx
 
Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptx
 
Data Structure.pptx
Data Structure.pptxData Structure.pptx
Data Structure.pptx
 

Recently uploaded

Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfRachmat Ramadhan H
 
定制英国白金汉大学毕业证(UCB毕业证书) 成绩单原版一比一
定制英国白金汉大学毕业证(UCB毕业证书)																			成绩单原版一比一定制英国白金汉大学毕业证(UCB毕业证书)																			成绩单原版一比一
定制英国白金汉大学毕业证(UCB毕业证书) 成绩单原版一比一ffjhghh
 
B2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxB2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxStephen266013
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxolyaivanovalion
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...Suhani Kapoor
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...Delhi Call girls
 
Invezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz1
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...Suhani Kapoor
 
Brighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingBrighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingNeil Barnes
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfMarinCaroMartnezBerg
 
VidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptxVidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptxolyaivanovalion
 
Week-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interactionWeek-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interactionfulawalesam
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfLars Albertsson
 
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service AmravatiVIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service AmravatiSuhani Kapoor
 
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% SecurePooja Nehwal
 
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAl Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAroojKhan71
 

Recently uploaded (20)

Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
 
定制英国白金汉大学毕业证(UCB毕业证书) 成绩单原版一比一
定制英国白金汉大学毕业证(UCB毕业证书)																			成绩单原版一比一定制英国白金汉大学毕业证(UCB毕业证书)																			成绩单原版一比一
定制英国白金汉大学毕业证(UCB毕业证书) 成绩单原版一比一
 
B2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxB2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docx
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptx
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
 
Invezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signals
 
Sampling (random) method and Non random.ppt
Sampling (random) method and Non random.pptSampling (random) method and Non random.ppt
Sampling (random) method and Non random.ppt
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
 
Brighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingBrighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data Storytelling
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
 
VidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptxVidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptx
 
Week-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interactionWeek-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interaction
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdf
 
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service AmravatiVIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
 
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
 
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
 
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in  KishangarhDelhi 99530 vip 56974 Genuine Escort Service Call Girls in  Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
 
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAl Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
 

CS261 Data Structures & Algorithms (Week-8) Lectures on Merge Sort and Queue

  • 1. CS261 DATA STRUCTURES & ALGORITHMS (WEEK-8) LECTURE-15 & 16 INTRODUCTION TO DATA STRUCTURES & ALGORITHMS Lecturer Azka Aziz Azka.a@scocs.edu.pk
  • 2. Data structures & Algorithms Lecture#15 Merge Sort
  • 3. Lecture Contents Divide & Conquer Divide & Conquer ….. Application (Merge Sort) mergeSort() Merge() Analysis
  • 4. Divide & Conquer Idea Distribute a larger problem into many small similar problems Solve every smaller problem recursively Combine results of smaller solutions to form the overall solution Usage A typical idea be to split a list of n items into two lists of n/2 size and try to sort them Consequence Running time of sorting can be improved from O(n2) to O(n log n)
  • 5. Divide & Conquer ….. Application (Merge Sort) Divide and conquer strategy is applicable in a huge number of computational problems. The first application of divide and conquer strategy is a simple and efficient sorting procedure called Merge Sort Input: a list of n numbers is provided as an array A[1…n] Output: a permutation of this sequence sorted in increasing order Method: Split Recursively, Sort, Merge
  • 6. Merge Sort Algorithm proc mergeSort(arr[1…n], p, r) if p < r then q  (p+r)/2 mergeSort(arr, p, q) mergeSort(arr, q+1, r) merge(arr, p, q, r) end if end proc Every pass of mergeSort() procedure consists of two recursive function calls followed by one call to merge
  • 7. Merge Sort Algorithm proc mergeSort(arr[1…n], p, r) if p < r then q  (p+r)/2 mergeSort(arr, p, q) mergeSort(arr, q+1, r) merge(arr, p, q, r) end if end proc mergeSort(arr, p, r) function checks whether p (index) is less than r (index) If it is so, it makes two calls to itself splitting the array into two halves Every further call splits array into further two halves with available indexes until p is not less than r (when will this happen?)
  • 8. Merge Sort Algorithm proc mergeSort(arr[1…n], p, r) if p < r then q  (p+r)/2 mergeSort(arr, p, q) mergeSort(arr, q+1, r) merge(arr, p, q, r) end if end proc Every further call splits array into further two halves with available indexes until p is not less than r (when will this happen?) At this point a merge(arr, p, q, r) call will me made to merge two halves into a sorted chunk
  • 10. merge() call merge(arr, p, q, r) assumes that two halves of array [p….q], [q+1….r] are sorted (Why is it? We have not sorted anything yet? Is there some statement in mergeSort() procedure that does the sorting part?) proc mergeSort(arr[1…n], p, r) if p < r then q  (p+r)/2 mergeSort(arr, p, q) mergeSort(arr, q+1, r) merge(arr, p, q, r) end if end proc
  • 11. mergeSort() calls … Visually We have not sorted anything yet? Is there some statement in mergeSort() procedure that does the sorting part? We just relied on a simple fact that splitting an array into equal halves will result into smaller and smaller arrays till there is only one element in array Is single element array sorted? Always?
  • 12. merge(arr, p, q, r) calls … Every merge() call receives three parameters (except the data array) i.e. p, q, r Values between indexes p….q and q+1……r are sorted (independent of each other) Having two sorted sub-arrays, merging part is easier:::
  • 13. merge(arr, p, q, r) calls … proc merge(arr, p, q, r) ip, kp, jq+1 temp[p…r] // using a temporary array while i ≤ q and j ≤ r do if arr[i] < arr[j] then temp[k++]  arr[i++] else temp[k++]  arr[j++] end if next
  • 14. merge(arr, p, q, r) calls … continued while i ≤ q do temp[k++]  arr[i++] next while j ≤ r do temp[k++]  arr[j++] next for i p to r do arr[i]  temp[i] next end proc
  • 15. merge() calls … Visually
  • 16. Merge Sort Analysis First we analyze merge() procedure First let us consider the running time of the procedure merge(A, p, q, r). Let n = r - p + 1 denote the total length of both the left and right sub- arrays. What is the running time of Merge as a function of n?
  • 17. Merge Sort Analysis Cost of mergeSort(with n elements) = cost of mergeSort(n/2 elements) + cost of mergeSort(n/2 elements) + cost of merge(n elements) MS(n) = MS(n/2) + MS(n/2)+M(n) MS(n) = 2MS(n/2) + M(n)
  • 18. Merge Sort Analysis T(1) = 1 T(2) = T(1) + T(1) + 2 = 1 + 1 + 2 = 4 T(3) = T(2) + T(1) + 3 = 4 + 1 + 3 = 8 T(4) = T(2) + T(2) + 4 = 8 + 8 + 4 = 12 T(5) = T(3) + T(2) + 5 = 8 + 4 + 5 = 17 . . . T(8) = T(4) + T(4) + 8 = 12 + 12 + 8 = 32 . . . T(16) = T(8) + T(8) + 16 = 32 + 32 + 16 = 80 T(32) = T(16) + T(16) + 32 = 80 + 80+ 32 = 192
  • 19. Merge Sort Analysis T(1) = 1 T(2) = T(1) + T(1) + 2 = 1 + 1 + 2 = 4 T(3) = T(2) + T(1) + 3 = 4 + 1 + 3 = 8 T(4) = T(2) + T(2) + 4 = 8 + 8 + 4 = 12 T(5) = T(3) + T(2) + 5 = 8 + 4 + 5 = 17 . . . T(8) = T(4) + T(4) + 8 = 12 + 12 + 8 = 32 . . . T(16) = T(8) + T(8) + 16 = 32 + 32 + 16 = 80 T(32) = T(16) + T(16) + 32 = 80 + 80+ 32 = 192 Is there some pattern? Let’s try T(n)/n = log n + 1 T(n) = n log n + n O(n log n)
  • 20. Merge Sort Analysis … Recurrence Relation T(n) = 2 T(n/2) + n Expanding we get T(n) = 2 (2T(n/4)+n/2)+n ….. ? How? = 4 T(n/4) + n + n = 8 T(n/8) + n + n + n = 16 T(n/16) + n + n + n + n = ……………. Now to solve it assuming that n = 2k, T(n) = 2k T(n/2k) + (n+n+n+n k items) T(n) = 2k T(n/2k) + kn
  • 21. Merge Sort Analysis … Recurrence Relation T(n) = 2 T(n/2) + n Expanding we get T(n) = 2 (2T(n/4)+n/2)+n = 4 T(n/4) + n + n = 8 T(n/8) + n + n + n = 16 T(n/16) + n + n + n + n = ……………. Now to solve it assuming that n = 2k, T(n) = 2k T(n/2k) + (n+n+n+n k Since n = 2k, i.e. k = log n T(n) = 2log n T(n/2log n) + (log n)n T(n) = n T(1) + n log n T(n) = n + n log n i.e. T(n) = O (n)
  • 22. Merge Sort Analysis … Recurrence Relation
  • 23. Data structures & Algorithms Lecture#16 Queue
  • 24. Queue Data Structure Queue is a data structure that is used to store data items. Data items are stored in Queue one by one. Stored data items when removed from Queue follow First In First Out order.
  • 25. Queue Queue maintains two control variables i. rear ii. front Data items are removed from Queue (deque() operation) using control variable ‘rear’ Data items are added to the Queue (enque() operation) using control variable ‘front’ Data item being enqued to Queue earliest will be removed from Queue earliest following First In First Out order (FIFO) Queue can be implemented using an Array as well as a Linked List
  • 26. Queue Operations … Operation Description Pseudocode Queue() Initialize ‘rear’ and ‘front’ with -1  Assign -1 to ‘rear’  Assign -1 to ‘front’ int is_empty() Returns TRUE if Queue is empty Returns FALSE if Queue is not empty  If ‘rear’ is less than ‘front’  Return FALSE  Otherwise  Return TRUE int is_full() Returns TRUE if Queue is empty Returns FALSE if Queue is not empty  If ‘rear’ is equal to -1 AND ‘front’ is equal to MAX-1 then  Return TRUE  Otherwise  Return FALSE
  • 27. Queue Operations … Operation Description Pseudocode int deque() Removes one item from queue using ‘rear’  If Queue is empty  It returns -1  Otherwise  Increment ‘rear’ by 1  Return value at current location of ‘rear’ void refresh() Relocates the queue elements so that empty positions are available post ‘front’ pointer  All elements are relocated to the smaller index positions making empty positions available post the ‘front’ locations  Assign -1 to ‘rear’ and value of (‘front’-’rear’-1) to ‘front’ void enque() Added an new data item to the Queue using ‘front’ pointer  If Queue is full, Nothing can be added  Else if ‘front’ is equal to MAX-1 then  Refresh is called, ‘front’ is incremented by 1, New element is added at ‘front’ location  Otherwise  ‘front’ is incremented by 1, New element is added at ‘front’ location
  • 28. Queue using array … implementation Implementation details and issues have been discussed during class
  • 29. Queue ADT … (implementing with linked list)
  • 30. Queue ADT … (implementing with linked list) QueueNode *Front; QueueNode *Rear; Queue(); int is_empty(); void enque(int); QueueNode* deque();
  • 31. Queue Operations … Operation Description Pseudocode Queue() Initialize ‘rear’ and ‘front’ with NULL  Assign NULL to ‘rear’  Assign NULL to ‘front’ int is_empty() Returns TRUE if Queue is empty Returns FALSE if Queue is not empty  If ‘front’ is equal to NULL  Return TRUE  Otherwise  Return FALSE QueueNode* deque() Removes one item from queue using ‘rear’  If Queue is empty  It returns NULL  Else if ‘rear’ and ‘front’ point to same node  Assign the node to QueueNode pointer ‘temp’  Assign NULL to ‘rear’ and ‘front’  Return ‘temp’  Else  Assign QueueNode pointed by ‘rear’ to ‘temp’  Assign ‘prev’ of ‘rear’ to ‘rear’  Set NULL to ‘next’ of ‘rear’  Return ‘temp’
  • 32. Queue Operations … Operation Description Pseudocode void enque(int) Added an new data item to the Queue using ‘front’ pointer  Create new node using the parameter of function and point it by ‘temp’  If Queue is empty  Assign ‘temp’ to ‘front’  Assign ‘temp’ to ‘rear’  Else  Assign ‘front’ to ‘next’ of ‘temp’  Assign ‘temp’ to ‘prev’ of ‘front’  Assign ‘temp’ to ‘front’
  • 33. Queue using array … implementation Implementation details and issues have been discussed during class
  • 34. Queue applications Level order tree traversal Any job management software following FIFO order Operating System maintains a queue of processes that are ready to execute Many computer based systems maintains a queue of messages to be communicated among their components Queue of people at any service point Queue of packets in data communication Queue of planes waiting for landing