SlideShare uma empresa Scribd logo
1 de 11
Searching & Sorting
Algorithms
Content
1. Linear Search
2. Binary Search
3. Selection Sort
4. Bubble Sort
5. Quick Sort
6. Merge Sort
Linear Search
In linear search, we look at each item in the list in turn, quitting once we find an item that
matches the search term or once we’ve reached the end of the list. Our “return value” is the
index at which the search term was found, or some indicator that the search term was not
found in the list.
Algorithm for linear search
for (each item in list)
{
compare search term to current item
if match,
save index of matching item
break
}
return index of matching item, or -1 if item not found
Performance of linear search
• Best case O(1): The best case occurs when the
search term is in the first slot in the array. The number
of comparisons in this case is 1.
• Worst case O(N) : The worst case occurs when the
search term is in the last slot in the array, or is not in
the array. The number of comparisons in this case is
equal to the size of the array. If our array has N items,
then it takes N comparisons in the worst case.
• Average case O(N/2): On average, the search term
will be somewhere in the middle of the array. The
number of comparisons in this case is approximately
N/2.
Binary Search
Binary search algorithm works on sorted arrays and uses divide and conquer technique. The
binary search begins by comparing the middle element of the array with the target value. If
the target value matches the middle element, its position in the array is returned. If the target
value is less than or greater than the middle element, the search continues in the lower or
upper half of the array, respectively, eliminating the other half from consideration.
Algorithm for binary search
set first = 1, last = N, mid = N/2
while (item not found and first < last)
{
compare search term to item at mid
if match , save index
break
else if search term is less than item at mid,
set last = mid-1
else
set first = mid+1
set mid = (first+last)/2
}
return index of matching item, or -1 if item not found
Binary Search (cont.)
Performance of linear search
• Best case O(1) : The best case occurs when the search term is in the middle slot in the array. The
number of comparisons in this case is 1O(1).
• Worst or Average Case O(log N) : The worst/average case occurs when the search term is in the
other that middle slot in the array, or is not in the array. The number of comparisons in this case is
equal to the size of the array. If our array has N items, then it takes N comparisons in the worst case.
Selection Sort
The idea behind selection sort is that we put a list in order by placing each item in
turn. In other words, we put the smallest item at the start of the list, then the next
smallest item at the second position in the list, and so on until the list is in order.
Algorithm for selection sort
for i=0 to N-2
{
set smallest = i
for j=i+1 to N-1
{
compare list[smallest] to list[j]
if list[smallest] == list[j]
smallest = j
}
swap list[i] and list[smallest]
}
O(N) in swaps and O(N^2) in comparisons
Bubble Sort
Bubble sort is similar to selection sort, on each pass through the algorithm, we place at
least one item in its proper location. The differences between bubble sort and selection
sort lie in how many times data is swapped and when the algorithm terminates.
Algorithm for bubble sort
for i=N-1 to 2
{
set swap flag to false
for j=1 to i
{
if list[j-1] > list[j]
swap list[j-1] and list[j]
set swap flag to true
}
if swap flag is false,
break.
}
O(N^2) in swaps and O(N^2) in comparisons
Quick Sort
Quicksort is a divide and conquer algorithm which relies on a partition operation: to
partition an array an element called a pivot is selected. All elements smaller than the pivot
are moved before it and all greater elements are moved after it. This can be done
efficiently in linear time and in-place. The lesser and greater sub-lists are then recursively
sorted.
O(N^2) in swaps and O(N^2) in
comparisons
Algorithm Steps for Quicksort
1. Pick an arbitrary element of the array
(the pivot).
2. Divide the array into two sub arrays,
those that are smaller and those that are
greater (the partition phase).
3. Recursively sort the sub arrays.
4. Put the pivot in the middle, between the
two sorted sub arrays to obtain the final
sorted array.
Merge Sort
Merge sort divides the array into two halves, sort each of those halves and then merges
them back together. For each half, it uses the same algorithm to divide and merge smaller
halves back. The smallest halves will just have one element each which is already sorted.
O(N log N) in swaps and O(N log N) in
comparisons
Algorithm Steps for Quicksort
1. divides the list into two smaller sub-lists
of approximately equal size
2. Recursively repeat this procedure till
only one element is left in the sub-list.
3. After this, various sorted sub-lists are
merged to form sorted parent list.
4. It will continue recursively until the
original sorted list created.
Summary
1. Selection sort’s advantage is that the number of swaps is O(N), since we perform at most
one data swap per pass through the algorithm. Its disadvantage is that it does not stop
early if the list is sorted; it looks at every element in the list in turn.
2. Bubble sort’s advantage is that it stops once it determines that the list is sorted. Its
disadvantage is that it is O(N^2) in both swaps and comparisons. For this reason, bubble
sort is actually the least efficient sorting method.
3. Quicksort is the fastest sort: it is O(N log N) in both the number of comparisons and the
number of swaps. The disadvantages of quicksort are that the algorithm is a bit tricky to
understand, and if we continually select poor pivots then the algorithm can approach
O(N^2) in the worst case.
4. Merge sort is as fast as quicksort: it is O(N log N) in both swaps and comparisons. The
disadvantage of merge sort is that it requires more copying of data from temporary lists
back to the “full” list, which slows down the algorithm a bit.
Questions?

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Searching algorithms
Searching algorithmsSearching algorithms
Searching algorithms
 
Algorithms Lecture 4: Sorting Algorithms I
Algorithms Lecture 4: Sorting Algorithms IAlgorithms Lecture 4: Sorting Algorithms I
Algorithms Lecture 4: Sorting Algorithms I
 
Binary search in data structure
Binary search in data structureBinary search in data structure
Binary search in data structure
 
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
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
 
Quicksort Presentation
Quicksort PresentationQuicksort Presentation
Quicksort Presentation
 
Linear and Binary search
Linear and Binary searchLinear and Binary search
Linear and Binary search
 
BCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHI
BCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHIBCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHI
BCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHI
 
Linear search-and-binary-search
Linear search-and-binary-searchLinear search-and-binary-search
Linear search-and-binary-search
 
Searching
SearchingSearching
Searching
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Algorithm: Quick-Sort
Algorithm: Quick-SortAlgorithm: Quick-Sort
Algorithm: Quick-Sort
 
Insertion sort
Insertion sort Insertion sort
Insertion sort
 
AVL Tree
AVL TreeAVL Tree
AVL Tree
 
linked lists in data structures
linked lists in data structureslinked lists in data structures
linked lists in data structures
 
Data Structures : hashing (1)
Data Structures : hashing (1)Data Structures : hashing (1)
Data Structures : hashing (1)
 
Priority queues
Priority queuesPriority queues
Priority queues
 
Selection sort
Selection sortSelection sort
Selection sort
 

Semelhante a Searching & Sorting Algorithms

DS - Unit 2 FINAL (2).pptx
DS - Unit 2 FINAL (2).pptxDS - Unit 2 FINAL (2).pptx
DS - Unit 2 FINAL (2).pptx
prakashvs7
 
Selection sort
Selection sortSelection sort
Selection sort
asra khan
 
Searching Sorting
Searching SortingSearching Sorting
Searching Sorting
guest2cb109
 
Ijcse13 05-01-048
Ijcse13 05-01-048Ijcse13 05-01-048
Ijcse13 05-01-048
vital vital
 
Ijcse13 05-01-048
Ijcse13 05-01-048Ijcse13 05-01-048
Ijcse13 05-01-048
vital vital
 

Semelhante a Searching & Sorting Algorithms (20)

DS - Unit 2 FINAL (2).pptx
DS - Unit 2 FINAL (2).pptxDS - Unit 2 FINAL (2).pptx
DS - Unit 2 FINAL (2).pptx
 
Data Structures_ Sorting & Searching
Data Structures_ Sorting & SearchingData Structures_ Sorting & Searching
Data Structures_ Sorting & Searching
 
Dsa – data structure and algorithms searching
Dsa – data structure and algorithms   searchingDsa – data structure and algorithms   searching
Dsa – data structure and algorithms searching
 
advanced searching and sorting.pdf
advanced searching and sorting.pdfadvanced searching and sorting.pdf
advanced searching and sorting.pdf
 
SEARCHING
SEARCHINGSEARCHING
SEARCHING
 
Unit v data structure-converted
Unit  v data structure-convertedUnit  v data structure-converted
Unit v data structure-converted
 
Sorting method data structure
Sorting method data structureSorting method data structure
Sorting method data structure
 
Linear Search
Linear SearchLinear Search
Linear Search
 
MODULE 5-Searching and-sorting
MODULE 5-Searching and-sortingMODULE 5-Searching and-sorting
MODULE 5-Searching and-sorting
 
Selection sort
Selection sortSelection sort
Selection sort
 
sorting and searching.pptx
sorting and searching.pptxsorting and searching.pptx
sorting and searching.pptx
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Sorting
SortingSorting
Sorting
 
Lecture_Oct26.pptx
Lecture_Oct26.pptxLecture_Oct26.pptx
Lecture_Oct26.pptx
 
Selection sort lab mannual
Selection sort lab mannualSelection sort lab mannual
Selection sort lab mannual
 
Searching Sorting
Searching SortingSearching Sorting
Searching Sorting
 
Different types of Shoring Algorithms with Animation
Different types of Shoring Algorithms with AnimationDifferent types of Shoring Algorithms with Animation
Different types of Shoring Algorithms with Animation
 
Analysis of Algorithm - Binary Search.pptx
Analysis of Algorithm - Binary Search.pptxAnalysis of Algorithm - Binary Search.pptx
Analysis of Algorithm - Binary Search.pptx
 
Ijcse13 05-01-048
Ijcse13 05-01-048Ijcse13 05-01-048
Ijcse13 05-01-048
 
Ijcse13 05-01-048
Ijcse13 05-01-048Ijcse13 05-01-048
Ijcse13 05-01-048
 

Mais de Rahul Jamwal (6)

Process & Mutlithreading
Process & MutlithreadingProcess & Mutlithreading
Process & Mutlithreading
 
Data Structures
Data StructuresData Structures
Data Structures
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
 
Virtual Memory Management
Virtual Memory ManagementVirtual Memory Management
Virtual Memory Management
 
C++ shared libraries and loading
C++ shared libraries and loadingC++ shared libraries and loading
C++ shared libraries and loading
 
C++ compilation process
C++ compilation processC++ compilation process
C++ compilation process
 

Último

%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Último (20)

Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 

Searching & Sorting Algorithms

  • 2. Content 1. Linear Search 2. Binary Search 3. Selection Sort 4. Bubble Sort 5. Quick Sort 6. Merge Sort
  • 3. Linear Search In linear search, we look at each item in the list in turn, quitting once we find an item that matches the search term or once we’ve reached the end of the list. Our “return value” is the index at which the search term was found, or some indicator that the search term was not found in the list. Algorithm for linear search for (each item in list) { compare search term to current item if match, save index of matching item break } return index of matching item, or -1 if item not found Performance of linear search • Best case O(1): The best case occurs when the search term is in the first slot in the array. The number of comparisons in this case is 1. • Worst case O(N) : The worst case occurs when the search term is in the last slot in the array, or is not in the array. The number of comparisons in this case is equal to the size of the array. If our array has N items, then it takes N comparisons in the worst case. • Average case O(N/2): On average, the search term will be somewhere in the middle of the array. The number of comparisons in this case is approximately N/2.
  • 4. Binary Search Binary search algorithm works on sorted arrays and uses divide and conquer technique. The binary search begins by comparing the middle element of the array with the target value. If the target value matches the middle element, its position in the array is returned. If the target value is less than or greater than the middle element, the search continues in the lower or upper half of the array, respectively, eliminating the other half from consideration. Algorithm for binary search set first = 1, last = N, mid = N/2 while (item not found and first < last) { compare search term to item at mid if match , save index break else if search term is less than item at mid, set last = mid-1 else set first = mid+1 set mid = (first+last)/2 } return index of matching item, or -1 if item not found
  • 5. Binary Search (cont.) Performance of linear search • Best case O(1) : The best case occurs when the search term is in the middle slot in the array. The number of comparisons in this case is 1O(1). • Worst or Average Case O(log N) : The worst/average case occurs when the search term is in the other that middle slot in the array, or is not in the array. The number of comparisons in this case is equal to the size of the array. If our array has N items, then it takes N comparisons in the worst case.
  • 6. Selection Sort The idea behind selection sort is that we put a list in order by placing each item in turn. In other words, we put the smallest item at the start of the list, then the next smallest item at the second position in the list, and so on until the list is in order. Algorithm for selection sort for i=0 to N-2 { set smallest = i for j=i+1 to N-1 { compare list[smallest] to list[j] if list[smallest] == list[j] smallest = j } swap list[i] and list[smallest] } O(N) in swaps and O(N^2) in comparisons
  • 7. Bubble Sort Bubble sort is similar to selection sort, on each pass through the algorithm, we place at least one item in its proper location. The differences between bubble sort and selection sort lie in how many times data is swapped and when the algorithm terminates. Algorithm for bubble sort for i=N-1 to 2 { set swap flag to false for j=1 to i { if list[j-1] > list[j] swap list[j-1] and list[j] set swap flag to true } if swap flag is false, break. } O(N^2) in swaps and O(N^2) in comparisons
  • 8. Quick Sort Quicksort is a divide and conquer algorithm which relies on a partition operation: to partition an array an element called a pivot is selected. All elements smaller than the pivot are moved before it and all greater elements are moved after it. This can be done efficiently in linear time and in-place. The lesser and greater sub-lists are then recursively sorted. O(N^2) in swaps and O(N^2) in comparisons Algorithm Steps for Quicksort 1. Pick an arbitrary element of the array (the pivot). 2. Divide the array into two sub arrays, those that are smaller and those that are greater (the partition phase). 3. Recursively sort the sub arrays. 4. Put the pivot in the middle, between the two sorted sub arrays to obtain the final sorted array.
  • 9. Merge Sort Merge sort divides the array into two halves, sort each of those halves and then merges them back together. For each half, it uses the same algorithm to divide and merge smaller halves back. The smallest halves will just have one element each which is already sorted. O(N log N) in swaps and O(N log N) in comparisons Algorithm Steps for Quicksort 1. divides the list into two smaller sub-lists of approximately equal size 2. Recursively repeat this procedure till only one element is left in the sub-list. 3. After this, various sorted sub-lists are merged to form sorted parent list. 4. It will continue recursively until the original sorted list created.
  • 10. Summary 1. Selection sort’s advantage is that the number of swaps is O(N), since we perform at most one data swap per pass through the algorithm. Its disadvantage is that it does not stop early if the list is sorted; it looks at every element in the list in turn. 2. Bubble sort’s advantage is that it stops once it determines that the list is sorted. Its disadvantage is that it is O(N^2) in both swaps and comparisons. For this reason, bubble sort is actually the least efficient sorting method. 3. Quicksort is the fastest sort: it is O(N log N) in both the number of comparisons and the number of swaps. The disadvantages of quicksort are that the algorithm is a bit tricky to understand, and if we continually select poor pivots then the algorithm can approach O(N^2) in the worst case. 4. Merge sort is as fast as quicksort: it is O(N log N) in both swaps and comparisons. The disadvantage of merge sort is that it requires more copying of data from temporary lists back to the “full” list, which slows down the algorithm a bit.