SlideShare a Scribd company logo
1 of 26
Prepared by,
DAVID RAJU KOLLURI
Diploma[CSE], B.Tech[CSE], M.Tech[CSE], (PhD[CSE])
Associate Professor, Dept of CSE
KESHAV MEMORIAL INSTITUTE OF
TECHNOLOGY
AN AUTONOMOUS INSTITUTION -
ACCREDITED BY NAAC WITH 'A' GRADE
( Powered by GENESIS )
AUTONOMOUS COLLEGE
UNIT-IV
SEARCHING & SORTING
SEARCHING
Definition: The process of finding an element, whether it is
present in the given list or not is called searching
 Searching for items is one of the most critical activities
in many applications.
 Examples of few search activities are spell checking,
searching for a name in list of names, opening files
etc.
The efficiency of a search depends on three things.
 The size and organization of the collection of data we
are searching.
 The search algorithm that is used.
 The efficiency of the test used to determine if the
search is successful.
Typesof Searching
 We will describe two searching methods in this
session.
 Linear Search: which starts searching from the
beginning of the list and checks each element until a
match is found.
 Binary search: which can only be used on a sorted
list. It successively divides the array into two parts,
then discards the part that cannot contain the
element we are searching for.
Searching involves following:
 Search List: The search list is simply a common
term for the collection of elements that we are
storing in. The elements in the list may or may
not be ordered (ascending or descending).
 Target Element: The element that we are
searching for. (Sometimes referred to as key
element).
Linear Search (Sequential Search):
 Linear Search is the traditional method of
searching. It is very simple but very poor in
performance at times.
 We begin search by comparing the first element
of the list with the target element. If it matches,
the search ends. Otherwise, we will move to next
element and compare. In this way, the target
element is compared with all the elements until a
match occurs.
 If the match do not occur and there are no more
elements to be compared, we conclude that
target element is absent in the list.
Linear Search
Successf
ul
KEY/TARGET
Element
Successful Search at
Position: 6
Linear Search(Function)
int LinearSearch(int a[ ] , int n, int key)
{
int i = 0;
while(i<n)
{
if (a[i] == key)
return(i);
i++;
}
return (-1);
}
performance for Linear search list of N items.
CASE MEANING NUMBER OF
ITERATION
TIME
COMPLEXITY
CASE
Best The item to be
searched is the
first item in the list
1 (1) Best
Average The item to be
searched is found
some where close
to middle of list
N/2 (N) Average
Worst The item to be
searched is the last
item in list, or it
does not exist at all
N (N) Worst
Binary Search:
 Binary Search is a vast improvement over the linear search but it
cannot always be used.
 For binary search to work, the items in the list must be in a sorted
order (either increasing (ascending) or decreasing (descending)
order similar to the way words in a dictionary are arranged.
 The pre-requisite for Binary Search method is that the input
elements list must be in the sorted order.
 The method starts with looking at the middle of the list. If it
matches with the target element, then the search is complete
Otherwise, the target element may be in the upper half or lower
half. The search progresses with the upper half if the target
element is greater than the middle element or with the lower half if
the target element is less than the middle.
 The process is continued until the target element is found or the
portion of the sub list to be searched is empty.
Binary Search
 Mid Point Calculation:
 Mid = (Low + High) / 2;
 If(Key == A[Mid]) then, return Mid+1;
 If(Key < A[Mid]) then Update High(High = Mid -
1)
 If(Key > A[Mid]) then Update Low(Low = Mid +
1)
Low Mid High
Key < A[Mid] Key > A[Mid]
0 1 2 3 4 5 6 7
Binary Search:
Mid = (Low +
High)/2;
High
Low
Target/Key
Element 23 Found at 6th(5+1)
Position
Binary Search:
int BinarySearch(int a[], int n, int key)
{
int low, high, midpos;
low = 0; high = n-1;
while(low <= high)
{
midpos = (low+high)/2;
if (key = = a[midpos])
return(midpos);
else
if(key<a[midpos])
high = midpos –1;
else
low = midpos + 1;
}
return(-1);
}
Key = 23
Total No of Comparisons
are: 3
Binary Search:
int r_binarysearch( int a[], int key, int low, int high)
{
int mid;
if (low>high)
return (-1)
mid = (low +high)/2;
if ( key = = a[mid])
return(mid);
if (key < a[mid])
r_binarysearch( a, key, low, mid-1);
else
r_binarysearch( a, key, mid+1,high);
}
Key = 23
Total No of Comparisons
are: 3
Binary Search:
 The recursive function determines whether the
search key lies in lower or upper half of the
array, then it calls itself on appropriate half.
 Each step of algorithm divides the list into two
parts and the search continues in one of them
and other is discarded.
 The search requires at most k steps where
2kn which results in time complexity of k =
log2n i.e., O(log n) for average and worst
cases.
Sorting Techniques
Definition:
 The process of getting data elements into order is called
Sorting.
 We have different techniques in Sorting
 Exchange Sort(Bubble Sort)
 Selection Sort
 Insertion Sort
 Quick Sort
 Merge Sort
 Tree Sort
 Radix Sort
Exchange Sort(BUBBLE SORT)
 Fundamental Mechanism: in an exchange sort is to
repeatedly make comparisons, and if required, swap
adjacent items. Bubble Sort is an example of the
exchange sort technique.
 Bubble Sort Process:
Always Adjacent two elements will be compared, if
required . At the end of the each and every pass
Largest/Smallest Element will be bubbled to Last(End)
Position
BubbleSort Mechanism
No of COMPARISIONS in each and every PASS
BubbleSort Mechanism
BubbleSort forStrings & Integers:
Bubble Sort for Strings:
void bubble_sort(char *str; int length)
{
for(i=0; i<length; i++)
for(j=i+1; j<length;j++)
{
if (str[i]>str[j])
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
printf(“Sorted String is %sn”,str);
}
Bubble Sort for Integers:
bubblesort(int a[], int n)
{
int pass, j, noexchange;
for(pass=0;pass<n-1;pass++)
{
noexchange=1;
for(j=0;j<n-pass-1;j++)
{
if(a[j]>a[j+1])
{
swap(a[j]>a[j+1]);
noexchange = 0;
}
}
if (noexchange);
return;
}
}
Sorting Techniques
Definition:
 The process of getting data elements into order is called
Sorting.
 We have different techniques in Sorting
 Exchange Sort(Bubble Sort)
 Selection Sort
 Insertion Sort
 Quick Sort
 Merge Sort
 Tree Sort
 Radix Sort
Out of Syllabus
Selection Sort:
 Assume First Element as Min element( Assumed
Minimum)
 Using Selection Sort, the Assumed Min is compared
with the remaining n-1 items, and whichever of all is
lowest, is called Actual Min will be used to swap the
Assumed Min.
 Then the second item from the list is taken and
compared with the remaining (n-2) items, if an item with
a value less than that of the second item is found on the
Selection Sort:
Sorting Completed
Selection Sort:
Function to perform Selection Sort:
void selection_sort(char *str, int len)
{
int i, j, min, swap;
char temp;
for(I=0; I<len; I++)
{
swap = 0;
min=I;
strcpy(temp , str[I]);
for (j = I+1; j<len; j++)
{
if( strcmp(str[j] ,temp)<0)
{
min=j;
strcpy(temp , str[j]);
swap =1;
}
}
if (swap)
{
strcpy(str[min] ,str[i]);
strcpy(str[i] ,temp);
}
}
}
Insertion Sort:
 Insertion sort is a simple sorting algorithm that
works the way we sort playing cards in our
hands.
Insertion Sort:
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
Searching_Sorting.pptx

More Related Content

Similar to Searching_Sorting.pptx

Similar to Searching_Sorting.pptx (20)

Unit 6 dsa SEARCHING AND SORTING
Unit 6 dsa SEARCHING AND SORTINGUnit 6 dsa SEARCHING AND SORTING
Unit 6 dsa SEARCHING AND SORTING
 
Chapter 14
Chapter 14Chapter 14
Chapter 14
 
Ocw chp6 2searchbinary
Ocw chp6 2searchbinaryOcw chp6 2searchbinary
Ocw chp6 2searchbinary
 
Data structure unit I part B
Data structure unit I part BData structure unit I part B
Data structure unit I part B
 
Lecture_Oct26.pptx
Lecture_Oct26.pptxLecture_Oct26.pptx
Lecture_Oct26.pptx
 
Linear and binary search
Linear and binary searchLinear and binary search
Linear and binary search
 
Searching in DSA that follow a dsa searching.pptx
Searching in DSA that follow a dsa searching.pptxSearching in DSA that follow a dsa searching.pptx
Searching in DSA that follow a dsa searching.pptx
 
Searching techniques in Data Structure And Algorithm
Searching techniques in Data Structure And AlgorithmSearching techniques in Data Structure And Algorithm
Searching techniques in Data Structure And Algorithm
 
Searching
SearchingSearching
Searching
 
search_sort.ppt
search_sort.pptsearch_sort.ppt
search_sort.ppt
 
arrays in c
arrays in carrays in c
arrays in c
 
seaching internal 2 ppt
seaching internal 2 pptseaching internal 2 ppt
seaching internal 2 ppt
 
Ch05 Black Jack
Ch05  Black  JackCh05  Black  Jack
Ch05 Black Jack
 
Searching in c language
Searching in c languageSearching in c language
Searching in c language
 
Searching and Sorting Unit II Part I.pptx
Searching and Sorting Unit II Part I.pptxSearching and Sorting Unit II Part I.pptx
Searching and Sorting Unit II Part I.pptx
 
sorting and searching.pptx
sorting and searching.pptxsorting and searching.pptx
sorting and searching.pptx
 
Binary search in ds
Binary search in dsBinary search in ds
Binary search in ds
 
Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptx
 
Binary Search Algorithm.pptx
Binary Search Algorithm.pptxBinary Search Algorithm.pptx
Binary Search Algorithm.pptx
 
searching in data structure.pptx
searching in data structure.pptxsearching in data structure.pptx
searching in data structure.pptx
 

Recently uploaded

Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...Call Girls in Nagpur High Profile
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 

Recently uploaded (20)

Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 

Searching_Sorting.pptx

  • 1. Prepared by, DAVID RAJU KOLLURI Diploma[CSE], B.Tech[CSE], M.Tech[CSE], (PhD[CSE]) Associate Professor, Dept of CSE KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY AN AUTONOMOUS INSTITUTION - ACCREDITED BY NAAC WITH 'A' GRADE ( Powered by GENESIS ) AUTONOMOUS COLLEGE UNIT-IV SEARCHING & SORTING
  • 2. SEARCHING Definition: The process of finding an element, whether it is present in the given list or not is called searching  Searching for items is one of the most critical activities in many applications.  Examples of few search activities are spell checking, searching for a name in list of names, opening files etc. The efficiency of a search depends on three things.  The size and organization of the collection of data we are searching.  The search algorithm that is used.  The efficiency of the test used to determine if the search is successful.
  • 3. Typesof Searching  We will describe two searching methods in this session.  Linear Search: which starts searching from the beginning of the list and checks each element until a match is found.  Binary search: which can only be used on a sorted list. It successively divides the array into two parts, then discards the part that cannot contain the element we are searching for.
  • 4. Searching involves following:  Search List: The search list is simply a common term for the collection of elements that we are storing in. The elements in the list may or may not be ordered (ascending or descending).  Target Element: The element that we are searching for. (Sometimes referred to as key element).
  • 5. Linear Search (Sequential Search):  Linear Search is the traditional method of searching. It is very simple but very poor in performance at times.  We begin search by comparing the first element of the list with the target element. If it matches, the search ends. Otherwise, we will move to next element and compare. In this way, the target element is compared with all the elements until a match occurs.  If the match do not occur and there are no more elements to be compared, we conclude that target element is absent in the list.
  • 7. Linear Search(Function) int LinearSearch(int a[ ] , int n, int key) { int i = 0; while(i<n) { if (a[i] == key) return(i); i++; } return (-1); }
  • 8. performance for Linear search list of N items. CASE MEANING NUMBER OF ITERATION TIME COMPLEXITY CASE Best The item to be searched is the first item in the list 1 (1) Best Average The item to be searched is found some where close to middle of list N/2 (N) Average Worst The item to be searched is the last item in list, or it does not exist at all N (N) Worst
  • 9. Binary Search:  Binary Search is a vast improvement over the linear search but it cannot always be used.  For binary search to work, the items in the list must be in a sorted order (either increasing (ascending) or decreasing (descending) order similar to the way words in a dictionary are arranged.  The pre-requisite for Binary Search method is that the input elements list must be in the sorted order.  The method starts with looking at the middle of the list. If it matches with the target element, then the search is complete Otherwise, the target element may be in the upper half or lower half. The search progresses with the upper half if the target element is greater than the middle element or with the lower half if the target element is less than the middle.  The process is continued until the target element is found or the portion of the sub list to be searched is empty.
  • 10. Binary Search  Mid Point Calculation:  Mid = (Low + High) / 2;  If(Key == A[Mid]) then, return Mid+1;  If(Key < A[Mid]) then Update High(High = Mid - 1)  If(Key > A[Mid]) then Update Low(Low = Mid + 1) Low Mid High Key < A[Mid] Key > A[Mid] 0 1 2 3 4 5 6 7
  • 11. Binary Search: Mid = (Low + High)/2; High Low Target/Key Element 23 Found at 6th(5+1) Position
  • 12. Binary Search: int BinarySearch(int a[], int n, int key) { int low, high, midpos; low = 0; high = n-1; while(low <= high) { midpos = (low+high)/2; if (key = = a[midpos]) return(midpos); else if(key<a[midpos]) high = midpos –1; else low = midpos + 1; } return(-1); } Key = 23 Total No of Comparisons are: 3
  • 13. Binary Search: int r_binarysearch( int a[], int key, int low, int high) { int mid; if (low>high) return (-1) mid = (low +high)/2; if ( key = = a[mid]) return(mid); if (key < a[mid]) r_binarysearch( a, key, low, mid-1); else r_binarysearch( a, key, mid+1,high); } Key = 23 Total No of Comparisons are: 3
  • 14. Binary Search:  The recursive function determines whether the search key lies in lower or upper half of the array, then it calls itself on appropriate half.  Each step of algorithm divides the list into two parts and the search continues in one of them and other is discarded.  The search requires at most k steps where 2kn which results in time complexity of k = log2n i.e., O(log n) for average and worst cases.
  • 15. Sorting Techniques Definition:  The process of getting data elements into order is called Sorting.  We have different techniques in Sorting  Exchange Sort(Bubble Sort)  Selection Sort  Insertion Sort  Quick Sort  Merge Sort  Tree Sort  Radix Sort
  • 16. Exchange Sort(BUBBLE SORT)  Fundamental Mechanism: in an exchange sort is to repeatedly make comparisons, and if required, swap adjacent items. Bubble Sort is an example of the exchange sort technique.  Bubble Sort Process: Always Adjacent two elements will be compared, if required . At the end of the each and every pass Largest/Smallest Element will be bubbled to Last(End) Position
  • 17. BubbleSort Mechanism No of COMPARISIONS in each and every PASS
  • 19. BubbleSort forStrings & Integers: Bubble Sort for Strings: void bubble_sort(char *str; int length) { for(i=0; i<length; i++) for(j=i+1; j<length;j++) { if (str[i]>str[j]) { temp = str[i]; str[i] = str[j]; str[j] = temp; } } printf(“Sorted String is %sn”,str); } Bubble Sort for Integers: bubblesort(int a[], int n) { int pass, j, noexchange; for(pass=0;pass<n-1;pass++) { noexchange=1; for(j=0;j<n-pass-1;j++) { if(a[j]>a[j+1]) { swap(a[j]>a[j+1]); noexchange = 0; } } if (noexchange); return; } }
  • 20. Sorting Techniques Definition:  The process of getting data elements into order is called Sorting.  We have different techniques in Sorting  Exchange Sort(Bubble Sort)  Selection Sort  Insertion Sort  Quick Sort  Merge Sort  Tree Sort  Radix Sort Out of Syllabus
  • 21. Selection Sort:  Assume First Element as Min element( Assumed Minimum)  Using Selection Sort, the Assumed Min is compared with the remaining n-1 items, and whichever of all is lowest, is called Actual Min will be used to swap the Assumed Min.  Then the second item from the list is taken and compared with the remaining (n-2) items, if an item with a value less than that of the second item is found on the
  • 23. Selection Sort: Function to perform Selection Sort: void selection_sort(char *str, int len) { int i, j, min, swap; char temp; for(I=0; I<len; I++) { swap = 0; min=I; strcpy(temp , str[I]); for (j = I+1; j<len; j++) { if( strcmp(str[j] ,temp)<0) { min=j; strcpy(temp , str[j]); swap =1; } } if (swap) { strcpy(str[min] ,str[i]); strcpy(str[i] ,temp); } } }
  • 24. Insertion Sort:  Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands.
  • 25. Insertion Sort: void insertionSort(int arr[], int n) { int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } }