SlideShare a Scribd company logo
 ALGORITHMS
 PRIORITY QUEUES
 HEAPS
 HEAP SORT
 MERGE SORT
 QUICK SORT
 BINARY SEARCH
 FINDING THE MAXIMUM AND MINIMUM
 ALGORITHM IS A FINITE SET OF WELL
DEFINED
COPUTATIONAL WRITTEN IN A PROPER
SEQENCE IN ORER TO SOLVE A PROBLEM.
 CRITERIA
 INPUT OUTPUT
 DEFINITENESS
 FINITENESS
 EFFECTIVENESS
Input- There should be 0 or more inputs supplied
externally to the algorithm.
Output- There should be at least 1 output obtained.
Definiteness- Every step of the algorithm should be
clear and well defined.
Finiteness- The algorithm should have finite number
of steps.
Correctness- Every step of the algorithm must
generate a correct output.
 ADD:INTEGER a,b,c
1.Read a & b
2.Add a & b
3.Store the sum of a & b to c
4.Print c
 in c, exp(1) in c, exp(2)
void add(int a,int b) int add(int a,int b){
int c; int c;
C= a+b; c=a+b;
Print(“%d”,c); return c;
} }
 Priority queue data structure is an abstract data type
that provides a way to maintain a set of elements, each
with an associated value called key.
 There are two kinds of priority queues: a max-priority
queue and a min-priority queue. In both kinds, the
priority queue stores a collection of elements and is
always able to provide the most “extreme” element,
which is the only way to interact with the priority
queue.
 For the remainder of this section, we will discuss max-
priority queues. Min-priority queues are analogous.
•insert / enqueue − add an item to the rear of the
queue.
•remove / dequeue − remove an item from the
front of the queue.
Priority Queue Representation
data structures and algorithms Unit 3
data structures and algorithms Unit 3
 Size ():
 Return the number of entries in the queue.
 isEmpty():
 Test whether the queue is empty.
 Min():
 Return(do not remove) an entry with smallest key.
 insert(k,x):
 Insert an entry with key k and value x.
 Remove min():
 Remove and return the entry with smallest key.
A heap is a data structure that stores a
collection of object(with keys),and has the
following properties:
 Complete Binary tree
 Heap order
 The first major step involves transforming the
complete tree into a heap.
 The second major step is to perform the a actual sort
by extracting the largest or lowerst element from the
root and transforming the remaining tree into a heap.
 Max Heap
 Min Heap
 Heap property is a binary tree with special
characteristics. It can be classified into two types:
I. Max-Heap
II. Min Heap
I. Max Heap: If the parent nodes are greater than their
child nodes, it is called a Max-Heap.
II. Min Heap: If the parent nodes are smaller than their
child nodes, it is called a Min-Heap.
data structures and algorithms Unit 3
Heap sort is a comparison based sorting
algorithm.
It is a special tree-based data structure.
Heap sort is similar to selection sort. The only
difference is, it finds largest element and places
the it at the end.
This sort is not a stable sort. It requires a
constant space for sorting a list.
It is very fast and widely used for sorting.
1. Shape Property
2. Heap Property
1. Shape property represents all the nodes or levels
of the tree are fully filled. Heap data structure is a
complete binary tree.
2.Heap property is a binary tree with special
characteristics. It can be classified into two types:
data structures and algorithms Unit 3
#include <stdio.h>
void main()
{
int heap[10], no, i, j, c, root, temp;
printf("n Enter no of elements :");
scanf("%d", &no);
printf("n Enter the nos : ");
for (i = 0; i < no; i++)
scanf("%d", &heap[i]);
for (i = 1; i < no; i++)
{
c = i;
do
{
root = (c - 1) / 2;
if (heap[root] < heap[c]) /* to create MAX heap
array */
{
temp = heap[root];
heap[root] = heap[c];
heap[c] = temp;
}
c = root;
} while (c != 0);
}
printf("Heap array : ");
for (i = 0; i < no; i++)
printf("%dt ", heap[i]);
for (j = no - 1; j >= 0; j--)
{
temp = heap[0];
heap[0] = heap[j]; /* swap max element
with rightmost leaf element */
heap[j] = temp;
root = 0;
do
{
c = 2 * root + 1; /* left node of root
element */
if ((heap[c] < heap[c + 1]) && c < j-1)
c++;
if (heap[root]<heap[c] && c<j) /* again
rearrange to max heap array */
{
temp = heap[root];
heap[root] = heap[c];
heap[c] = temp;
}
root = c;
} while (c < j);
}
printf("n The sorted array is : ");
for (i = 0; i < no; i++)
printf("t %d", heap[i]);
printf("n Complexity : n Best case =
Avg case = Worst case = O(n logn) n");
}
data structures and algorithms Unit 3
 Quick sort is also known as Partition-exchange sort
based on the rule of Divide and Conquer.
 It is a highly efficient sorting algorithm.
 Quick sort is the quickest comparison-based sorting
algorithm.
 It is very fast and requires less additional space, only
O(n log n) space is required.
 Quick sort picks an element as pivot and partitions the
array around the picked pivot.
1. First element as pivot 2. Last element as
pivot
3. Random element as
pivot
4.Median as pivot
Step 1: Choose the highest index value as pivot.
Step 2: Take two variables to point left and right of the list excluding
pivot.
Step 3: Left points to the low index.
Step 4: Right points to the high index.
Step 5: While value at left < (Less than) pivot move right.
Step 6: While value at right > (Greater than) pivot move left.
Step 7: If both Step 5 and Step 6 does not match, swap left and right.
Step 8: If left = (Less than or Equal to) right, the point
data structures and algorithms Unit 3
data structures and algorithms Unit 3
#include<stdio.h>
#include<conio.h>
//quick Sort function to Sort Integer array list
void quicksort(int array[], int firstIndex, int lastIndex)
{
//declaaring index variables
int pivotIndex, temp, index1, index2;
if(firstIndex < lastIndex)
{
//assigninh first element index as pivot element
pivotIndex = firstIndex;
index1 = firstIndex;
index2 = lastIndex;
//Sorting in Ascending order with quick sort
while(index1 < index2)
{
while(array[index1] <= array[pivotIndex] && index1
< lastIndex)
{
index1++;
}
while(array[index2]>array[pivotIndex])
{
index2--;
}
if(index1<index2)
{
//Swapping opertation
temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
}
//At the end of first iteration, swap pivot element with
index2 element
temp = array[pivotIndex];
array[pivotIndex] = array[index2];
array[index2] = temp;
//Recursive call for quick sort, with partiontioning
quicksort(array, firstIndex, index2-1);
quicksort(array, index2+1, lastIndex);
}
}
int main()
{
//Declaring variables
int array[100],n,i;
//Number of elements in array form user input
printf("Enter the number of element you want to Sort :
");
scanf("%d",&n);
//code to ask to enter elements from user equal
to n
printf("Enter Elements in the list : ");
for(i = 0; i < n; i++)
{
scanf("%d",&array[i]);
}
//calling quickSort function defined above
quicksort(array,0,n-1);
//print sorted array
printf("Sorted elements: ");
for(i=0;i<n;i++)
printf(" %d",array[i]);
getch();
return 0;
}
data structures and algorithms Unit 3
Merge sort is a sorting technique based on
divide and conquer technique. With worst-case
time complexity being Ο(n log n), it is one of the
most respected algorithms.
Merge sort first divides the array into equal
halves and then combines them in a sorted
manner.
To understand merge sort, we take an unsorted array as
the following −
We know that merge sort first divides the whole array
iteratively into equal halves unless the atomic values are
achieved. We see here that an array of 8 items is divided
into two arrays of size 4.
This does not change the sequence of appearance
of items in the original. Now we divide these two
arrays into halves.
We further divide these arrays and we achieve
atomic value which can no more be divided.
Now, we combine them in exactly the same manner as they were broken
down. Please note the color codes given to these lists. we first compare
the element for each list and then combine them into another list in a
sorted manner. We see that 14 and 33 are in sorted positions. We compare
27 and 10 and in the target list of 2 values we put 10 first, followed by 27.
We change the order of 19 and 35 whereas 42 and 44 are placed
sequentially.
In the next iteration of the combining phase, we compare lists of two data
values, and merge them into a list of found data values placing all in a
sorted order.
In the next iteration of the combining phase, we compare
lists of two data values, and merge them into a list of
found data values placing all in a sorted order.
After the final merging, the list should look like this −
 Merge sort keeps on dividing the list into equal halves
until it can no more be divided. By definition, if it is only
one element in the list, it is sorted. Then, merge sort
combines the smaller sorted lists keeping the new list
sorted too.
 Step 1 − if it is only one element in
the list it is already sorted, return.
 Step 2 − divide the list recursively
into two halves until it can no more be
divided.
 Step 3 − merge the smaller lists into
new list in sorted order.
Searching-
 Searching is a process of finding a particular element
among several given elements.
 The search is successful if the required element is found.
 Otherwise, the search is unsuccessful.
Searching Algorithms-
 Searching Algorithms are a family of algorithms used for
the purpose of searching.
 The searching of an element in the given array may be
carried out in the following two ways-
•Linear Search
•Binary Search
Binary Search-
 Binary Search is one of the fastest searching
algorithms.
 It is used for finding the location of an element
in a linear array.
 It works on the principle of divide and conquer
technique.
Binary Search Algorithm-
•There is a linear array ‘a’ of size ‘n’.
•Binary search algorithm is being used to
search an element ‘item’ in this linear array.
•If search ends in success, it sets loc to
the index of the element otherwise it sets loc to -1.
•Variables beg and end keeps track of the index
of the first and last element of the array or sub array
in which the element is being searched at that instant.
•Variable mid keeps track of the index of the middle
element of that array or sub array in which the element is
being searched at that instant.
1.Begin
2.Set end = n-1
3.Set mid = (beg + end) / 2
4.while((beg <= end)and(a[mid] ≠ item)) do
5.if(item < a[mid]) then
6.Set end = mid - 1
7.else
8.Set beg = mid + 1
9.endif
10.Set beg = 0
11.Set mid = (beg + end) / 2
12endwhile
13.if(beg > end) then
14.Set loc = -1
15.else
16.Set loc = mid
17.endif
 We are given the following sorted linear array.
 Element 15 has to be searched in it using Binary Search
Algorithm.
Step-01:
 To begin with, we take beg=0 and end=6.
 We compute location of the middle element as-mid
= (beg + end) / 2
= (0 + 6) / 2
= 3
 Here, a[mid] = a[3] = 20 ≠ 15 and beg < end.
 So, we start next iteration.
Step-02:
Since a[mid] = 20 > 15, so we take end = mid – 1
= 3 – 1 = 2 whereas beg remains unchanged.
We compute location of the middle element
as-
mid
= (beg + end) / 2
= (0 + 2) / 2
= 1
Here, a[mid] = a[1] = 10 ≠ 15 and beg < end.
So, we start next iteration.
Step-03:
Since a[mid] = 10 < 15, so we take beg =
mid + 1 = 1 + 1 = 2 whereas end remains
unchanged.
We compute location of the middle
element as-
mid
= (beg + end) / 2
= (2 + 2) / 2
= 2
Here, a[mid] = a[2] = 15 which matches
to the element being searched.
So, our search terminates in success
and index 2 is returned.
Problem
Given an array of integers, find the maximum and minimum of the array.
Constraint
Find the answer in minimum number of comparisons.
Brute force
We can keep two variables named max and min. We can iterate over the list
and compare each number with the min and the max, if the number is greater
than the max update max, if the number is less than the min, update the min.
 In this brute force solution the number of comparison is 2*n.
Better solution
If rather than comparing each number with max and min,
we can first compare the numbers in pair with each other.
Then compare the larger number with max and compare
the smaller number with min. in this way the number of
comparison for a pair of numbers are 3.
So number of comparisons are 1.5 *n.
public class FindMinMax
{
public static void main(String[] args){
int[] arr = {4, 3, 5, 1, 2, 6, 9, 2, 10, 11};
int max = arr[0];
int min = arr[0];
int i = 0;
for (; i < arr.length / 2; i++){
int num1 = arr[i * 2];
int num2 = arr[i * 2 + 1];
if (num1 >= num2){
if (num1 > max)
max = num1;
if (num2 < min) min = num2;
}
else { if (num2 > max)
max = num;
if (num1 < min)
min = num1;
}
}
if (i * 2 < arr.length)
{
int num = arr[i * 2];
if (num > max)
max = num;
if (num < min)
min = num;
}
System.out.println("maximum= " + max);
System.out.println("minimum= " + min);
}
}
Ad

Recommended

PPT
3.8 quick sort
Krish_ver2
 
PPT
Stack and queue
Katang Isip
 
PPTX
Lecture optimal binary search tree
Divya Ks
 
PPTX
Operating system architecture
Sabin dumre
 
PPT
Binary Search
kunj desai
 
PDF
Token, Pattern and Lexeme
A. S. M. Shafi
 
PPTX
8 queens problem using back tracking
Tech_MX
 
PPTX
page replacement.pptx
homipeh
 
PDF
Lec 4 expert systems
Eyob Seyfu
 
PPTX
Insertion sort
MYER301
 
PPTX
Graph coloring using backtracking
shashidharPapishetty
 
PPTX
Top TCS Interview Questions And Answers | How to Crack An Interview At TCS | ...
Simplilearn
 
PPT
Expert Systems
Jason Hando
 
PPTX
Lecture 25 hill climbing
Hema Kashyap
 
PPTX
Scenario based methods
JoshuaU1
 
PPTX
N queens using backtracking
srilekhagourishetty
 
PDF
Heap Tree.pdf
manahilzulfiqar6
 
PPTX
Divide and conquer 1
Kumar
 
PPTX
Forests in data structures and algorithms .pptx
rahmathshiraz1
 
PDF
Effective Algorithm for n Fibonacci Number By: Professor Lili Saghafi
Professor Lili Saghafi
 
PPTX
Logical reasoning
Slideshare
 
PPTX
Collision in Hashing.pptx
NBACriteria2SICET
 
PPT
05 architectural styles
Majong DevJfu
 
PPTX
Binary Tree in Data Structure
Meghaj Mallick
 
PPTX
Queues in C++
Vineeta Garg
 
PPTX
Depth first search [dfs]
DEEPIKA T
 
PDF
Heap, quick and merge sort
Dr. Mohammad Amir Khusru Akhtar (Ph.D)
 
PPTX
Searching and Sorting Algorithms in Data Structures
poongothai11
 

More Related Content

What's hot (20)

PDF
Lec 4 expert systems
Eyob Seyfu
 
PPTX
Insertion sort
MYER301
 
PPTX
Graph coloring using backtracking
shashidharPapishetty
 
PPTX
Top TCS Interview Questions And Answers | How to Crack An Interview At TCS | ...
Simplilearn
 
PPT
Expert Systems
Jason Hando
 
PPTX
Lecture 25 hill climbing
Hema Kashyap
 
PPTX
Scenario based methods
JoshuaU1
 
PPTX
N queens using backtracking
srilekhagourishetty
 
PDF
Heap Tree.pdf
manahilzulfiqar6
 
PPTX
Divide and conquer 1
Kumar
 
PPTX
Forests in data structures and algorithms .pptx
rahmathshiraz1
 
PDF
Effective Algorithm for n Fibonacci Number By: Professor Lili Saghafi
Professor Lili Saghafi
 
PPTX
Logical reasoning
Slideshare
 
PPTX
Collision in Hashing.pptx
NBACriteria2SICET
 
PPT
05 architectural styles
Majong DevJfu
 
PPTX
Binary Tree in Data Structure
Meghaj Mallick
 
PPTX
Queues in C++
Vineeta Garg
 
PPTX
Depth first search [dfs]
DEEPIKA T
 
Lec 4 expert systems
Eyob Seyfu
 
Insertion sort
MYER301
 
Graph coloring using backtracking
shashidharPapishetty
 
Top TCS Interview Questions And Answers | How to Crack An Interview At TCS | ...
Simplilearn
 
Expert Systems
Jason Hando
 
Lecture 25 hill climbing
Hema Kashyap
 
Scenario based methods
JoshuaU1
 
N queens using backtracking
srilekhagourishetty
 
Heap Tree.pdf
manahilzulfiqar6
 
Divide and conquer 1
Kumar
 
Forests in data structures and algorithms .pptx
rahmathshiraz1
 
Effective Algorithm for n Fibonacci Number By: Professor Lili Saghafi
Professor Lili Saghafi
 
Logical reasoning
Slideshare
 
Collision in Hashing.pptx
NBACriteria2SICET
 
05 architectural styles
Majong DevJfu
 
Binary Tree in Data Structure
Meghaj Mallick
 
Queues in C++
Vineeta Garg
 
Depth first search [dfs]
DEEPIKA T
 

Similar to data structures and algorithms Unit 3 (20)

PDF
Heap, quick and merge sort
Dr. Mohammad Amir Khusru Akhtar (Ph.D)
 
PPTX
Searching and Sorting Algorithms in Data Structures
poongothai11
 
PDF
Data structures arrays
maamir farooq
 
PDF
advanced searching and sorting.pdf
haramaya university
 
PDF
Sorting
Kariman Karm Gabaa
 
PDF
Sorting
A. S. M. Shafi
 
PPT
SEARCHING AND SORTING ALGORITHMS
Gokul Hari
 
PPT
Advanced s and s algorithm.ppt
LegesseSamuel
 
PPTX
Chapter3.pptx
ASMAALWADEE2
 
PPTX
هياكلبيانات
Rafal Edward
 
DOCX
MODULE 5-Searching and-sorting
nikshaikh786
 
PPTX
VCE Unit 04vv.pptx
skilljiolms
 
PPTX
Chapter 2 Sorting and Searching .pptx.soft
kuruabeje7
 
PDF
DS UNIT 1.pdf
SeethaDinesh
 
PDF
DS UNIT 1.pdf
SeethaDinesh
 
PPTX
PYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUES
vanithasivdc
 
PPTX
what is sorting algorithm and implementation.pptx
TanaTech
 
PPTX
Lecture 1 Abstract Data Types of Complexity Analysis of Big Oh Notation.pptx
yhrcxd8wpm
 
PPTX
Lecture 1 Abstract Data Types of Complexity Analysis of Big Oh Notation.pptx
yhrcxd8wpm
 
PPTX
data structures with algorithms vtu 2023 notes.pptx
hemanthkumar40680
 
Heap, quick and merge sort
Dr. Mohammad Amir Khusru Akhtar (Ph.D)
 
Searching and Sorting Algorithms in Data Structures
poongothai11
 
Data structures arrays
maamir farooq
 
advanced searching and sorting.pdf
haramaya university
 
SEARCHING AND SORTING ALGORITHMS
Gokul Hari
 
Advanced s and s algorithm.ppt
LegesseSamuel
 
Chapter3.pptx
ASMAALWADEE2
 
هياكلبيانات
Rafal Edward
 
MODULE 5-Searching and-sorting
nikshaikh786
 
VCE Unit 04vv.pptx
skilljiolms
 
Chapter 2 Sorting and Searching .pptx.soft
kuruabeje7
 
DS UNIT 1.pdf
SeethaDinesh
 
DS UNIT 1.pdf
SeethaDinesh
 
PYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUES
vanithasivdc
 
what is sorting algorithm and implementation.pptx
TanaTech
 
Lecture 1 Abstract Data Types of Complexity Analysis of Big Oh Notation.pptx
yhrcxd8wpm
 
Lecture 1 Abstract Data Types of Complexity Analysis of Big Oh Notation.pptx
yhrcxd8wpm
 
data structures with algorithms vtu 2023 notes.pptx
hemanthkumar40680
 
Ad

Recently uploaded (20)

PPTX
NSUMD_M1 Library Orientation_June 11, 2025.pptx
Julie Sarpy
 
PPTX
Photo chemistry Power Point Presentation
mprpgcwa2024
 
PDF
Hurricane Helene Application Documents Checklists
Mebane Rash
 
PPTX
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
PPTX
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT Kharagpur Quiz Club
 
PDF
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
 
PPTX
Great Governors' Send-Off Quiz 2025 Prelims IIT KGP
IIT Kharagpur Quiz Club
 
PPTX
YSPH VMOC Special Report - Measles Outbreak Southwest US 6-14-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
PDF
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
Kweku Zurek
 
PDF
Gladiolous Cultivation practices by AKL.pdf
kushallamichhame
 
PPTX
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
Mayvel Nadal
 
PPTX
Code Profiling in Odoo 18 - Odoo 18 Slides
Celine George
 
PDF
Learning Styles Inventory for Senior High School Students
Thelma Villaflores
 
PPTX
How to Manage Different Customer Addresses in Odoo 18 Accounting
Celine George
 
PDF
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
KaryanaTantri21
 
PPTX
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
parmarjuli1412
 
PPTX
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
parmarjuli1412
 
PDF
VCE Literature Section A Exam Response Guide
jpinnuck
 
PPTX
How payment terms are configured in Odoo 18
Celine George
 
PDF
English 3 Quarter 1_LEwithLAS_Week 1.pdf
DeAsisAlyanajaneH
 
NSUMD_M1 Library Orientation_June 11, 2025.pptx
Julie Sarpy
 
Photo chemistry Power Point Presentation
mprpgcwa2024
 
Hurricane Helene Application Documents Checklists
Mebane Rash
 
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT Kharagpur Quiz Club
 
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
 
Great Governors' Send-Off Quiz 2025 Prelims IIT KGP
IIT Kharagpur Quiz Club
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 6-14-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
Kweku Zurek
 
Gladiolous Cultivation practices by AKL.pdf
kushallamichhame
 
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
Mayvel Nadal
 
Code Profiling in Odoo 18 - Odoo 18 Slides
Celine George
 
Learning Styles Inventory for Senior High School Students
Thelma Villaflores
 
How to Manage Different Customer Addresses in Odoo 18 Accounting
Celine George
 
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
KaryanaTantri21
 
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
parmarjuli1412
 
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
parmarjuli1412
 
VCE Literature Section A Exam Response Guide
jpinnuck
 
How payment terms are configured in Odoo 18
Celine George
 
English 3 Quarter 1_LEwithLAS_Week 1.pdf
DeAsisAlyanajaneH
 
Ad

data structures and algorithms Unit 3

  • 1.  ALGORITHMS  PRIORITY QUEUES  HEAPS  HEAP SORT  MERGE SORT  QUICK SORT  BINARY SEARCH  FINDING THE MAXIMUM AND MINIMUM
  • 2.  ALGORITHM IS A FINITE SET OF WELL DEFINED COPUTATIONAL WRITTEN IN A PROPER SEQENCE IN ORER TO SOLVE A PROBLEM.  CRITERIA  INPUT OUTPUT  DEFINITENESS  FINITENESS  EFFECTIVENESS
  • 3. Input- There should be 0 or more inputs supplied externally to the algorithm. Output- There should be at least 1 output obtained. Definiteness- Every step of the algorithm should be clear and well defined. Finiteness- The algorithm should have finite number of steps. Correctness- Every step of the algorithm must generate a correct output.
  • 4.  ADD:INTEGER a,b,c 1.Read a & b 2.Add a & b 3.Store the sum of a & b to c 4.Print c  in c, exp(1) in c, exp(2) void add(int a,int b) int add(int a,int b){ int c; int c; C= a+b; c=a+b; Print(“%d”,c); return c; } }
  • 5.  Priority queue data structure is an abstract data type that provides a way to maintain a set of elements, each with an associated value called key.  There are two kinds of priority queues: a max-priority queue and a min-priority queue. In both kinds, the priority queue stores a collection of elements and is always able to provide the most “extreme” element, which is the only way to interact with the priority queue.  For the remainder of this section, we will discuss max- priority queues. Min-priority queues are analogous.
  • 6. •insert / enqueue − add an item to the rear of the queue. •remove / dequeue − remove an item from the front of the queue. Priority Queue Representation
  • 9.  Size ():  Return the number of entries in the queue.  isEmpty():  Test whether the queue is empty.  Min():  Return(do not remove) an entry with smallest key.  insert(k,x):  Insert an entry with key k and value x.  Remove min():  Remove and return the entry with smallest key.
  • 10. A heap is a data structure that stores a collection of object(with keys),and has the following properties:  Complete Binary tree  Heap order
  • 11.  The first major step involves transforming the complete tree into a heap.  The second major step is to perform the a actual sort by extracting the largest or lowerst element from the root and transforming the remaining tree into a heap.
  • 12.  Max Heap  Min Heap
  • 13.  Heap property is a binary tree with special characteristics. It can be classified into two types: I. Max-Heap II. Min Heap I. Max Heap: If the parent nodes are greater than their child nodes, it is called a Max-Heap. II. Min Heap: If the parent nodes are smaller than their child nodes, it is called a Min-Heap.
  • 15. Heap sort is a comparison based sorting algorithm. It is a special tree-based data structure. Heap sort is similar to selection sort. The only difference is, it finds largest element and places the it at the end. This sort is not a stable sort. It requires a constant space for sorting a list. It is very fast and widely used for sorting.
  • 16. 1. Shape Property 2. Heap Property 1. Shape property represents all the nodes or levels of the tree are fully filled. Heap data structure is a complete binary tree. 2.Heap property is a binary tree with special characteristics. It can be classified into two types:
  • 18. #include <stdio.h> void main() { int heap[10], no, i, j, c, root, temp; printf("n Enter no of elements :"); scanf("%d", &no); printf("n Enter the nos : "); for (i = 0; i < no; i++) scanf("%d", &heap[i]); for (i = 1; i < no; i++) { c = i; do
  • 19. { root = (c - 1) / 2; if (heap[root] < heap[c]) /* to create MAX heap array */ { temp = heap[root]; heap[root] = heap[c]; heap[c] = temp; } c = root; } while (c != 0); } printf("Heap array : "); for (i = 0; i < no; i++) printf("%dt ", heap[i]); for (j = no - 1; j >= 0; j--)
  • 20. { temp = heap[0]; heap[0] = heap[j]; /* swap max element with rightmost leaf element */ heap[j] = temp; root = 0; do { c = 2 * root + 1; /* left node of root element */ if ((heap[c] < heap[c + 1]) && c < j-1) c++; if (heap[root]<heap[c] && c<j) /* again rearrange to max heap array */ { temp = heap[root]; heap[root] = heap[c];
  • 21. heap[c] = temp; } root = c; } while (c < j); } printf("n The sorted array is : "); for (i = 0; i < no; i++) printf("t %d", heap[i]); printf("n Complexity : n Best case = Avg case = Worst case = O(n logn) n"); }
  • 23.  Quick sort is also known as Partition-exchange sort based on the rule of Divide and Conquer.  It is a highly efficient sorting algorithm.  Quick sort is the quickest comparison-based sorting algorithm.  It is very fast and requires less additional space, only O(n log n) space is required.  Quick sort picks an element as pivot and partitions the array around the picked pivot.
  • 24. 1. First element as pivot 2. Last element as pivot
  • 25. 3. Random element as pivot 4.Median as pivot
  • 26. Step 1: Choose the highest index value as pivot. Step 2: Take two variables to point left and right of the list excluding pivot. Step 3: Left points to the low index. Step 4: Right points to the high index. Step 5: While value at left < (Less than) pivot move right. Step 6: While value at right > (Greater than) pivot move left. Step 7: If both Step 5 and Step 6 does not match, swap left and right. Step 8: If left = (Less than or Equal to) right, the point
  • 29. #include<stdio.h> #include<conio.h> //quick Sort function to Sort Integer array list void quicksort(int array[], int firstIndex, int lastIndex) { //declaaring index variables int pivotIndex, temp, index1, index2; if(firstIndex < lastIndex) { //assigninh first element index as pivot element pivotIndex = firstIndex; index1 = firstIndex; index2 = lastIndex; //Sorting in Ascending order with quick sort while(index1 < index2)
  • 30. { while(array[index1] <= array[pivotIndex] && index1 < lastIndex) { index1++; } while(array[index2]>array[pivotIndex]) { index2--; } if(index1<index2) { //Swapping opertation temp = array[index1]; array[index1] = array[index2]; array[index2] = temp; } }
  • 31. //At the end of first iteration, swap pivot element with index2 element temp = array[pivotIndex]; array[pivotIndex] = array[index2]; array[index2] = temp; //Recursive call for quick sort, with partiontioning quicksort(array, firstIndex, index2-1); quicksort(array, index2+1, lastIndex); } } int main() { //Declaring variables int array[100],n,i; //Number of elements in array form user input printf("Enter the number of element you want to Sort : "); scanf("%d",&n);
  • 32. //code to ask to enter elements from user equal to n printf("Enter Elements in the list : "); for(i = 0; i < n; i++) { scanf("%d",&array[i]); } //calling quickSort function defined above quicksort(array,0,n-1); //print sorted array printf("Sorted elements: "); for(i=0;i<n;i++) printf(" %d",array[i]); getch(); return 0; }
  • 34. Merge sort is a sorting technique based on divide and conquer technique. With worst-case time complexity being Ο(n log n), it is one of the most respected algorithms. Merge sort first divides the array into equal halves and then combines them in a sorted manner.
  • 35. To understand merge sort, we take an unsorted array as the following − We know that merge sort first divides the whole array iteratively into equal halves unless the atomic values are achieved. We see here that an array of 8 items is divided into two arrays of size 4.
  • 36. This does not change the sequence of appearance of items in the original. Now we divide these two arrays into halves. We further divide these arrays and we achieve atomic value which can no more be divided.
  • 37. Now, we combine them in exactly the same manner as they were broken down. Please note the color codes given to these lists. we first compare the element for each list and then combine them into another list in a sorted manner. We see that 14 and 33 are in sorted positions. We compare 27 and 10 and in the target list of 2 values we put 10 first, followed by 27. We change the order of 19 and 35 whereas 42 and 44 are placed sequentially. In the next iteration of the combining phase, we compare lists of two data values, and merge them into a list of found data values placing all in a sorted order.
  • 38. In the next iteration of the combining phase, we compare lists of two data values, and merge them into a list of found data values placing all in a sorted order. After the final merging, the list should look like this −
  • 39.  Merge sort keeps on dividing the list into equal halves until it can no more be divided. By definition, if it is only one element in the list, it is sorted. Then, merge sort combines the smaller sorted lists keeping the new list sorted too.  Step 1 − if it is only one element in the list it is already sorted, return.  Step 2 − divide the list recursively into two halves until it can no more be divided.  Step 3 − merge the smaller lists into new list in sorted order.
  • 40. Searching-  Searching is a process of finding a particular element among several given elements.  The search is successful if the required element is found.  Otherwise, the search is unsuccessful. Searching Algorithms-  Searching Algorithms are a family of algorithms used for the purpose of searching.  The searching of an element in the given array may be carried out in the following two ways-
  • 42. Binary Search-  Binary Search is one of the fastest searching algorithms.  It is used for finding the location of an element in a linear array.  It works on the principle of divide and conquer technique.
  • 43. Binary Search Algorithm- •There is a linear array ‘a’ of size ‘n’. •Binary search algorithm is being used to search an element ‘item’ in this linear array. •If search ends in success, it sets loc to the index of the element otherwise it sets loc to -1. •Variables beg and end keeps track of the index of the first and last element of the array or sub array in which the element is being searched at that instant. •Variable mid keeps track of the index of the middle element of that array or sub array in which the element is being searched at that instant.
  • 44. 1.Begin 2.Set end = n-1 3.Set mid = (beg + end) / 2 4.while((beg <= end)and(a[mid] ≠ item)) do 5.if(item < a[mid]) then 6.Set end = mid - 1 7.else 8.Set beg = mid + 1 9.endif 10.Set beg = 0 11.Set mid = (beg + end) / 2 12endwhile 13.if(beg > end) then 14.Set loc = -1 15.else 16.Set loc = mid 17.endif
  • 45.  We are given the following sorted linear array.  Element 15 has to be searched in it using Binary Search Algorithm.
  • 46. Step-01:  To begin with, we take beg=0 and end=6.  We compute location of the middle element as-mid = (beg + end) / 2 = (0 + 6) / 2 = 3  Here, a[mid] = a[3] = 20 ≠ 15 and beg < end.  So, we start next iteration.
  • 47. Step-02: Since a[mid] = 20 > 15, so we take end = mid – 1 = 3 – 1 = 2 whereas beg remains unchanged. We compute location of the middle element as- mid = (beg + end) / 2 = (0 + 2) / 2 = 1 Here, a[mid] = a[1] = 10 ≠ 15 and beg < end. So, we start next iteration.
  • 48. Step-03: Since a[mid] = 10 < 15, so we take beg = mid + 1 = 1 + 1 = 2 whereas end remains unchanged. We compute location of the middle element as- mid = (beg + end) / 2 = (2 + 2) / 2 = 2 Here, a[mid] = a[2] = 15 which matches to the element being searched. So, our search terminates in success and index 2 is returned.
  • 49. Problem Given an array of integers, find the maximum and minimum of the array. Constraint Find the answer in minimum number of comparisons. Brute force We can keep two variables named max and min. We can iterate over the list and compare each number with the min and the max, if the number is greater than the max update max, if the number is less than the min, update the min.  In this brute force solution the number of comparison is 2*n.
  • 50. Better solution If rather than comparing each number with max and min, we can first compare the numbers in pair with each other. Then compare the larger number with max and compare the smaller number with min. in this way the number of comparison for a pair of numbers are 3. So number of comparisons are 1.5 *n.
  • 51. public class FindMinMax { public static void main(String[] args){ int[] arr = {4, 3, 5, 1, 2, 6, 9, 2, 10, 11}; int max = arr[0]; int min = arr[0]; int i = 0; for (; i < arr.length / 2; i++){ int num1 = arr[i * 2]; int num2 = arr[i * 2 + 1]; if (num1 >= num2){ if (num1 > max) max = num1; if (num2 < min) min = num2; }
  • 52. else { if (num2 > max) max = num; if (num1 < min) min = num1; } } if (i * 2 < arr.length) { int num = arr[i * 2]; if (num > max) max = num; if (num < min) min = num; } System.out.println("maximum= " + max); System.out.println("minimum= " + min); } }