SlideShare una empresa de Scribd logo
1 de 11
Searching and Sorting

   Topics
   • Sequential Search on an Unordered File
   • Binary Search




CMSC 104, Version 9/01
Common Problems
   • There are some very common problems that
       we use computers to solve:
        o    Searching through a lot of records for a specific
            record or set of records
        o   Placing records in order, which we call sorting
   • There are numerous algorithms to perform
       searches and sorts. We will briefly explore a
       few common ones.




CMSC 104, Version 9/01
Searching
 • A question you should always ask when selecting a
   search algorithm is “How fast does the search have
   to be?” The reason is that, in general, the faster
   the algorithm is, the more complex it is.
 • Bottom line: you don’t always need to use or
   should use the fastest algorithm.
 • Let’s explore the following search algorithms,
   keeping speed in mind.
    o Sequential (linear) search

    o Binary search



CMSC 104, Version 9/01
Sequential Search on an Unordered File

   • Basic algorithm:
        Get the search criterion (key)
        Get the first record from the file
        While ( (record != key) and (still more records) )
         Get the next record
        End_while


   • When do we know that there wasn’t a
       record in the file that matched the key?
CMSC 104, Version 9/01
Binary Search

   • If we have an ordered list and we know
     how many things are in the list (i.e.,
     number of records in a file), we can use a
     different strategy.
   • The binary search gets its name because
     the algorithm continually divides the list into
     two parts.



CMSC 104, Version 9/01
How a Binary Search Works



                            Always look at the
                            center value. Each
                            time you get to discard
                            half of the remaining
                            list.

                            Is this fast ?

CMSC 104, Version 9/01
How Fast is a Binary Search?

   • Worst case: 11 items in the list took 4 tries
   • How about the worst case for a list with 32
       items ?
        o   1st try - list has 16 items
        o   2nd try - list has 8 items
        o   3rd try - list has 4 items
        o   4th try - list has 2 items
        o   5th try - list has 1 item


CMSC 104, Version 9/01
How Fast is a Binary Search? (con’t)

       List has 250 items    List has 512 items

       1st try - 125 items   1st try - 256 items
       2nd try - 63 items    2nd try - 128 items
       3rd try - 32 items    3rd try - 64 items
       4th try - 16 items    4th try - 32 items
       5th try - 8 items     5th try - 16 items
       6th try - 4 items     6th try - 8 items
       7th try - 2 items     7th try - 4 items
       8th try - 1 item      8th try - 2 items
                             9th try - 1 item
CMSC 104, Version 9/01
What’s the Pattern?

   • List of 11 took 4 tries
   • List of 32 took 5 tries
   • List of 250 took 8 tries
   • List of 512 took 9 tries


   • 32 = 25 and 512 = 29
   • 8 < 11 < 16     23 < 11 < 24
   • 128 < 250 < 256               27 < 250 < 28

CMSC 104, Version 9/01
A Very Fast Algorithm!

   • How long (worst case) will it take to find an
       item in a list 30,000 items long?
           210 = 1024                 213 = 8192
           211 = 2048                 214 = 16384
           212 = 4096                 215 = 32768

   • So, it will take only 15 tries!



CMSC 104, Version 9/01                               1
Lg n Efficiency

   • We say that the binary search algorithm
       runs in log2 n time. (Also written as lg n)
   • Lg n means the log to the base 2 of some
     value of n.
   • 8 = 23 lg 8 = 3 16 = 24 lg 16 = 4
   • There are no algorithms that run faster than
     lg n time.



CMSC 104, Version 9/01                               1

Más contenido relacionado

Destacado

Polyphase circuit vbr
Polyphase circuit   vbrPolyphase circuit   vbr
Polyphase circuit vbr
Vijay Raskar
 
The Loss of Intellectual Property in the Digital Age: What Companies can d…
The Loss of Intellectual Property in the Digital Age: What Companies can d…The Loss of Intellectual Property in the Digital Age: What Companies can d…
The Loss of Intellectual Property in the Digital Age: What Companies can d…
Christopher Kranich
 

Destacado (20)

3-phase circuit
3-phase circuit3-phase circuit
3-phase circuit
 
Polyphase circuit vbr
Polyphase circuit   vbrPolyphase circuit   vbr
Polyphase circuit vbr
 
badgediva.com
badgediva.combadgediva.com
badgediva.com
 
The Loss of Intellectual Property in the Digital Age: What Companies can d…
The Loss of Intellectual Property in the Digital Age: What Companies can d…The Loss of Intellectual Property in the Digital Age: What Companies can d…
The Loss of Intellectual Property in the Digital Age: What Companies can d…
 
Three phase-circuits
Three phase-circuitsThree phase-circuits
Three phase-circuits
 
3phase circuits
3phase circuits3phase circuits
3phase circuits
 
Veranderdiagnose (een samenvatting)
Veranderdiagnose (een samenvatting)Veranderdiagnose (een samenvatting)
Veranderdiagnose (een samenvatting)
 
Pn junction
Pn junctionPn junction
Pn junction
 
Type of data @ Web Mining Discussion
Type of data @ Web Mining DiscussionType of data @ Web Mining Discussion
Type of data @ Web Mining Discussion
 
Identifing And Controlling Intellectual Property Loss Exposures
Identifing And Controlling Intellectual Property Loss ExposuresIdentifing And Controlling Intellectual Property Loss Exposures
Identifing And Controlling Intellectual Property Loss Exposures
 
Feedback amplifiers
Feedback amplifiersFeedback amplifiers
Feedback amplifiers
 
Oscillators
OscillatorsOscillators
Oscillators
 
Factors Influencing Knowledge Management
Factors Influencing Knowledge ManagementFactors Influencing Knowledge Management
Factors Influencing Knowledge Management
 
Oscillators
OscillatorsOscillators
Oscillators
 
Purpose-Driven Organizations: a Conceptual Model
Purpose-Driven Organizations: a Conceptual ModelPurpose-Driven Organizations: a Conceptual Model
Purpose-Driven Organizations: a Conceptual Model
 
Trends that will influence the future of knowledge work
Trends that will influence the future of knowledge workTrends that will influence the future of knowledge work
Trends that will influence the future of knowledge work
 
Feedback
FeedbackFeedback
Feedback
 
Web mining slides
Web mining slidesWeb mining slides
Web mining slides
 
Web Mining
Web Mining Web Mining
Web Mining
 
Intellectual Property 101
Intellectual Property 101Intellectual Property 101
Intellectual Property 101
 

Similar a Sorting searching

Similar a Sorting searching (20)

L24Searching&Sorting.ppt
L24Searching&Sorting.pptL24Searching&Sorting.ppt
L24Searching&Sorting.ppt
 
L24Searching&Sorting.ppt
L24Searching&Sorting.pptL24Searching&Sorting.ppt
L24Searching&Sorting.ppt
 
AAXGF.ppt
AAXGF.pptAAXGF.ppt
AAXGF.ppt
 
ABCD.ppt
ABCD.pptABCD.ppt
ABCD.ppt
 
Building a Large Scale SEO/SEM Application with Apache Solr: Presented by Rah...
Building a Large Scale SEO/SEM Application with Apache Solr: Presented by Rah...Building a Large Scale SEO/SEM Application with Apache Solr: Presented by Rah...
Building a Large Scale SEO/SEM Application with Apache Solr: Presented by Rah...
 
lecture1-intro.ppt
lecture1-intro.pptlecture1-intro.ppt
lecture1-intro.ppt
 
lecture1-intro.ppt
lecture1-intro.pptlecture1-intro.ppt
lecture1-intro.ppt
 
introduction into IR
introduction into IRintroduction into IR
introduction into IR
 
Handling and Analyzing Large Telemetry Data Sets
Handling and Analyzing Large Telemetry Data SetsHandling and Analyzing Large Telemetry Data Sets
Handling and Analyzing Large Telemetry Data Sets
 
CS2: A Searchable Cryptographic Cloud Storage System
CS2: A Searchable Cryptographic Cloud Storage SystemCS2: A Searchable Cryptographic Cloud Storage System
CS2: A Searchable Cryptographic Cloud Storage System
 
Building a CRM on top of ElasticSearch
Building a CRM on top of ElasticSearchBuilding a CRM on top of ElasticSearch
Building a CRM on top of ElasticSearch
 
ORMs Meet SQL
ORMs Meet SQLORMs Meet SQL
ORMs Meet SQL
 
Internet-scale Real-time Code Clone Search via Multi-level Indexing
Internet-scale Real-time Code Clone Search via Multi-level IndexingInternet-scale Real-time Code Clone Search via Multi-level Indexing
Internet-scale Real-time Code Clone Search via Multi-level Indexing
 
Good practices (and challenges) for reproducibility
Good practices (and challenges) for reproducibilityGood practices (and challenges) for reproducibility
Good practices (and challenges) for reproducibility
 
SearchAlgorithm.pdf
SearchAlgorithm.pdfSearchAlgorithm.pdf
SearchAlgorithm.pdf
 
Logstash family introduction
Logstash family introductionLogstash family introduction
Logstash family introduction
 
Approximate "Now" is Better Than Accurate "Later"
Approximate "Now" is Better Than Accurate "Later"Approximate "Now" is Better Than Accurate "Later"
Approximate "Now" is Better Than Accurate "Later"
 
Geek Sync | Guide to Understanding and Monitoring Tempdb
Geek Sync | Guide to Understanding and Monitoring TempdbGeek Sync | Guide to Understanding and Monitoring Tempdb
Geek Sync | Guide to Understanding and Monitoring Tempdb
 
PostgreSQL worst practices, version PGConf.US 2017 by Ilya Kosmodemiansky
PostgreSQL worst practices, version PGConf.US 2017 by Ilya KosmodemianskyPostgreSQL worst practices, version PGConf.US 2017 by Ilya Kosmodemiansky
PostgreSQL worst practices, version PGConf.US 2017 by Ilya Kosmodemiansky
 
Fake It 'Til You Make It
Fake It 'Til You Make ItFake It 'Til You Make It
Fake It 'Til You Make It
 

Más de ForwardBlog Enewzletter (7)

Compile time polymorphism
Compile time polymorphismCompile time polymorphism
Compile time polymorphism
 
Constructors & destructors
Constructors & destructorsConstructors & destructors
Constructors & destructors
 
Oo ps
Oo psOo ps
Oo ps
 
Parameter passing to_functions_in_c
Parameter passing to_functions_in_cParameter passing to_functions_in_c
Parameter passing to_functions_in_c
 
Propositional logic
Propositional logicPropositional logic
Propositional logic
 
Stack a Data Structure
Stack a Data StructureStack a Data Structure
Stack a Data Structure
 
Presentation on graphs
Presentation on graphsPresentation on graphs
Presentation on graphs
 

Último

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

Sorting searching

  • 1. Searching and Sorting Topics • Sequential Search on an Unordered File • Binary Search CMSC 104, Version 9/01
  • 2. Common Problems • There are some very common problems that we use computers to solve: o Searching through a lot of records for a specific record or set of records o Placing records in order, which we call sorting • There are numerous algorithms to perform searches and sorts. We will briefly explore a few common ones. CMSC 104, Version 9/01
  • 3. Searching • A question you should always ask when selecting a search algorithm is “How fast does the search have to be?” The reason is that, in general, the faster the algorithm is, the more complex it is. • Bottom line: you don’t always need to use or should use the fastest algorithm. • Let’s explore the following search algorithms, keeping speed in mind. o Sequential (linear) search o Binary search CMSC 104, Version 9/01
  • 4. Sequential Search on an Unordered File • Basic algorithm: Get the search criterion (key) Get the first record from the file While ( (record != key) and (still more records) ) Get the next record End_while • When do we know that there wasn’t a record in the file that matched the key? CMSC 104, Version 9/01
  • 5. Binary Search • If we have an ordered list and we know how many things are in the list (i.e., number of records in a file), we can use a different strategy. • The binary search gets its name because the algorithm continually divides the list into two parts. CMSC 104, Version 9/01
  • 6. How a Binary Search Works Always look at the center value. Each time you get to discard half of the remaining list. Is this fast ? CMSC 104, Version 9/01
  • 7. How Fast is a Binary Search? • Worst case: 11 items in the list took 4 tries • How about the worst case for a list with 32 items ? o 1st try - list has 16 items o 2nd try - list has 8 items o 3rd try - list has 4 items o 4th try - list has 2 items o 5th try - list has 1 item CMSC 104, Version 9/01
  • 8. How Fast is a Binary Search? (con’t) List has 250 items List has 512 items 1st try - 125 items 1st try - 256 items 2nd try - 63 items 2nd try - 128 items 3rd try - 32 items 3rd try - 64 items 4th try - 16 items 4th try - 32 items 5th try - 8 items 5th try - 16 items 6th try - 4 items 6th try - 8 items 7th try - 2 items 7th try - 4 items 8th try - 1 item 8th try - 2 items 9th try - 1 item CMSC 104, Version 9/01
  • 9. What’s the Pattern? • List of 11 took 4 tries • List of 32 took 5 tries • List of 250 took 8 tries • List of 512 took 9 tries • 32 = 25 and 512 = 29 • 8 < 11 < 16 23 < 11 < 24 • 128 < 250 < 256 27 < 250 < 28 CMSC 104, Version 9/01
  • 10. A Very Fast Algorithm! • How long (worst case) will it take to find an item in a list 30,000 items long? 210 = 1024 213 = 8192 211 = 2048 214 = 16384 212 = 4096 215 = 32768 • So, it will take only 15 tries! CMSC 104, Version 9/01 1
  • 11. Lg n Efficiency • We say that the binary search algorithm runs in log2 n time. (Also written as lg n) • Lg n means the log to the base 2 of some value of n. • 8 = 23 lg 8 = 3 16 = 24 lg 16 = 4 • There are no algorithms that run faster than lg n time. CMSC 104, Version 9/01 1