SlideShare ist ein Scribd-Unternehmen logo
1 von 15
Downloaden Sie, um offline zu lesen
Week 9
Searching and
Sorting
Copyright Warning
                             COMMONWEALTH OF AUSTRALIA
                               Copyright Regulations 1969
                                                     WARNING
 This material has been copied and communicated to you by or
    on behalf of Bond University pursuant to Part VB of the
                  Copyright Act 1968 (the Act).
The material in this communication may be subject to copyright
 under the Act. Any further copying or communication of this
  material by you may be the subject of copyright protection
                        under the Act.


Do not remove this notice.

© 2004 Pearson Addison-Wesley. All rights reserved             4-2
Sorting
Frequently, we want our collections of data sorted (in ascending
   order, alphabetically, etc.)

There are many algorithms for sorting data

Considerations:
• How to compare elements?
   – numerically, in ascending or descending order
   – alphabetically
   – highest card, etc.
• How are elements stored?
   – e.g., if an array, need to move elements around until they are
      in the right order
• What is the best method?
   – need a way to characterise different sorting methods to decide
      which is best for the problem at hand

© 2004 Pearson Addison-Wesley. All rights reserved                 4-3
Selection Sort
Selection sort pseudo-code algorithm:

problem: sort the array A into ascending order
1. Find the position of the smallest element of A
2. Swap the smallest with the element at position A[0]
3. Find the position of the smallest element of A from
   position 1 to the end of A
4. Swap this smallest element with the element at
   position A[1]
5. Find the position of the smallest element of A from
   position 2 to the end of A
6. Swap with A[2]
7. Repeat this process until the whole array has been
   sorted
© 2004 Pearson Addison-Wesley. All rights reserved       4-4
Selection Sort Example
                                    (from Phil Stocks’ slides)

         original array:                     A: 11 2            3   7 5
                                                     0    1     2   3   4



A: 11 2                      3        7 5                           A: 2 11             3       7 5
 from 1
    0                         2       3       4                             0       1       2   3    4


A: 2              11        3         7 5                           A: 2        3       11      7 5
            0         1       2       3       4                             0       1       2   3    4


A: 2              3       11          7 5                           A: 2        3       5       7 11
            0         1       2       3       4                             0       1    2      3    4


A: 2              3         5       7       11                      A: 2        3       5       7 11
            0         1       2       3       4                           0         1    2      3    4


A: 2              3         5         7 11                          A: 2        3       5       7 11
            0         1       2       3       4          done             0         1    2      3    4
© 2004 Pearson Addison-Wesley. All rights reserved                                                  4-5
Selection Sort in Java:
              Stepwise Refinement
 // Perform a selection sort of the array A
 public void selSort ( int [ ] A ) {

       // iterate over indices up to second from the end
       (A.length – 2)
       for ( int i = 0; i < A.length – 1; i++) {
         // find position, k, of smallest element of remaining
       array:
         // i.e., position, k, of smallest in A[i .. A.length – 1]
         <need code here>

           // swap elements at positions i and k
           <need code here>
       }
 }
© 2004 Pearson Addison-Wesley. All rights reserved                   4-6
Selection Sort in Java:
              Stepwise Refinement
  // Perform a selection sort of the array A
  public void selSort ( int [ ] A ) {

        // iterate over indices up to second from the end (A.length – 2)
        for ( int i = 0; i < A.length – 1; i++) {
          // find position, k, of smallest element of remaining array:
          // i.e., position, k, of smallest in A[i .. A.length – 1]
          int k;
          <need code here>

            // swap elements at positions i and k
            int temp = a[i];
            a[i] = a[k];
            a[k] = temp;
        }
  }
© 2004 Pearson Addison-Wesley. All rights reserved                         4-7
Selection Sort in Java:
              Stepwise Refinement
// Perform a selection sort of the array A
public void selSort ( int [ ] A ) {

    // iterate over indices up to second from the end (A.length – 2)
    for ( int i = 0; i < A.length – 1; i++) {
      // find position, k, of smallest element of remaining array:
      // i.e., position, k, of smallest in A[i .. A.length – 1]
      int k = i;                                              Note the initialisation
      for (int j = i+1; j < A.length; j++)                    to i
            if ( A[j] < A[k] )
                  k = j;

        // swap elements at positions i and k
        int temp = A[i];
        A[i] = A[k];
        A[k] = temp;
    }
© 2004 Pearson Addison-Wesley. All rights reserved                            4-8
Selection Sort Analysis
  How good is selection sort? How fast is it?

  Most often executed statement:
     – statement body of innermost for-loop: if ( A[j] < A[k] ) k = j;

  How many executions of this statement for an array of length n?
     – first iteration of outer loop:  n-1 times
     – second iteration of outer loop: n-2 times
     – …
     – last iteration of outer loop:   1 time
     ⇒ (n-1) + (n-2) + … + 2 + 1
         = n (n-1) / 2
         this is proportional to n2

  We call selection sort an order n2 algorithm ( written: O(n2) )

© 2004 Pearson Addison-Wesley. All rights reserved                       4-9
How slow is O(n2)?
  Example, sort population of England, approximately
    50 million

  n2 = 5 x 107 x 5 x 107
      = 2.5 x 1015

  I.e., on the order of 2.5 x 1015 comparisons executed!

  (At 100 million comparisons per second (optimistic)
    this would take nearly a year to run.)


© 2004 Pearson Addison-Wesley. All rights reserved   4-10
Searching
Very common to search through collections of
  data looking for a particular element

Again, efficiency is a realistic concern

Consider Linear Search from before:How fast is it?
                                                      How many
boolean found = false;                                comparisons?

for (int index=0; index<SIZE && !found; index+        For an array of length n,
    +)                                                on the order of n
    if (A[index] == X)                                comparisons
              found = true;
                                                      Linear search is order
                                                      n ( O(n) )
 © 2004 Pearson Addison-Wesley. All rights reserved                       4-11
Searching Ordered Data
        Common to keep collections in sorted order. We
          can use that knowledge to speed up searching


Linear Search II:
                                                     boolean found = false;
(of sorted array)
                                                     for (int index=0; index<SIZE && !found;
•     proceed from front to                              index++) {
      back
                                                         if ( A[index] > X)
•     if value at position
      equals X then found                                          break;
•     if value of position is
      greater than X, X                                  if (A[index] == X)
      cannot be in the array,                                      found = true;
      so break                                       }
                           Linear Search II is still order n
© 2004 Pearson Addison-Wesley. All rights reserved                                             4-12
Twenty Questions
  I’m thinking of a number between 1 and 1,000,000

  Can you guess it in 20 questions?

  “Is it smaller than 500,000?”                      “yes”
  “Is it smaller than 250,000?”                      “no”
  “Is it smaller than 375,000?”                      “no”
  etc.

  Each question halves the remaining viable numbers

  How many questions to search 1,000,000? I.e., how many times can
    1,000,000 be divided by 2?
     – 220 = 1, 048, 576
     – log2(1,048,576) = 20
     – log2(1,000,000) < 20     therefore, 20 questions is enough!



© 2004 Pearson Addison-Wesley. All rights reserved             4-13
Twenty Questions
Find the value X in a sorted array A in the range A[0] to A[size]:
• Start with the middle element. If X > A[middle], search the top half. If X <
   A[middle], search the bottom half. In either case, now searching a subarray
   half the original size.
• The search continues by checking the middle element of the subarray and
   further halving the search space.
• End when find a location P in 0..Size such that A[P-1] < X <= A[P]. If the
   current position is at one end then X < A[0] or X > A[Size]
                                                              A
    Find 27:           -5        2           5       9   13       14   27   31   44   51


                       -5        2           5       9   13       14   27   31   44   51


                       -5        2           5       9   13       14   27   31   44   51


© 2004 Pearson Addison-Wesley. All rights reserved                                     4-14
Binary Search Procedure
int binSearch ( int [ ] A, int x) // return index of x in A
{
             int left = 0; right = A.length-1; mid;

                      if (A.length == 0 || x < A[0]) return –1;
                      if ( x > A[right] ) return A.length;

                      while (left < right) {
                                       // assertion: A[left]< x < A[right]
                                        mid = (left + right) / 2 ;
                                        if ( x == A[mid] )
                                                return (x);

                                      if (x < A[mid] )
                        right = mid - 1;
                    else
                        left = mid + 1;
           }

           if (x == A[left]) return left;
           else       return –1;
    © 2004 Pearson Addison-Wesley. All rights reserved                       4-15
}

Weitere ähnliche Inhalte

Was ist angesagt?

Preparation Data Structures 01 introduction
Preparation Data Structures 01 introductionPreparation Data Structures 01 introduction
Preparation Data Structures 01 introductionAndres Mendez-Vazquez
 
Data Structure and Algorithms Arrays
Data Structure and Algorithms ArraysData Structure and Algorithms Arrays
Data Structure and Algorithms ArraysManishPrajapati78
 
Data Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching algorithmsData Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching algorithmsAbdullah Al-hazmy
 
The Ring programming language version 1.7 book - Part 90 of 196
The Ring programming language version 1.7 book - Part 90 of 196The Ring programming language version 1.7 book - Part 90 of 196
The Ring programming language version 1.7 book - Part 90 of 196Mahmoud Samir Fayed
 
The Ring programming language version 1.5.1 book - Part 70 of 180
The Ring programming language version 1.5.1 book - Part 70 of 180The Ring programming language version 1.5.1 book - Part 70 of 180
The Ring programming language version 1.5.1 book - Part 70 of 180Mahmoud Samir Fayed
 
Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016BienvenidoVelezUPR
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arraysIntro C# Book
 
Row major and column major in 2 d
Row major and column major in 2 dRow major and column major in 2 d
Row major and column major in 2 dnikhilarora2211
 
Preparation Data Structures 04 array linear_list
Preparation Data Structures 04 array linear_listPreparation Data Structures 04 array linear_list
Preparation Data Structures 04 array linear_listAndres Mendez-Vazquez
 

Was ist angesagt? (20)

Array
ArrayArray
Array
 
Array
ArrayArray
Array
 
Icom4015 lecture14-f16
Icom4015 lecture14-f16Icom4015 lecture14-f16
Icom4015 lecture14-f16
 
MA3696 Lecture 5
MA3696 Lecture 5MA3696 Lecture 5
MA3696 Lecture 5
 
Preparation Data Structures 01 introduction
Preparation Data Structures 01 introductionPreparation Data Structures 01 introduction
Preparation Data Structures 01 introduction
 
Jeop game-final-review
Jeop game-final-reviewJeop game-final-review
Jeop game-final-review
 
Arrays
ArraysArrays
Arrays
 
Data Structure and Algorithms Arrays
Data Structure and Algorithms ArraysData Structure and Algorithms Arrays
Data Structure and Algorithms Arrays
 
Data Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching algorithmsData Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching algorithms
 
The Ring programming language version 1.7 book - Part 90 of 196
The Ring programming language version 1.7 book - Part 90 of 196The Ring programming language version 1.7 book - Part 90 of 196
The Ring programming language version 1.7 book - Part 90 of 196
 
Unit 4 tree
Unit 4   treeUnit 4   tree
Unit 4 tree
 
Avl trees
Avl treesAvl trees
Avl trees
 
The Ring programming language version 1.5.1 book - Part 70 of 180
The Ring programming language version 1.5.1 book - Part 70 of 180The Ring programming language version 1.5.1 book - Part 70 of 180
The Ring programming language version 1.5.1 book - Part 70 of 180
 
IMT, col space again
IMT, col space againIMT, col space again
IMT, col space again
 
Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
 
Row major and column major in 2 d
Row major and column major in 2 dRow major and column major in 2 d
Row major and column major in 2 d
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Arrays
ArraysArrays
Arrays
 
Preparation Data Structures 04 array linear_list
Preparation Data Structures 04 array linear_listPreparation Data Structures 04 array linear_list
Preparation Data Structures 04 array linear_list
 

Ähnlich wie Week09

Review session2
Review session2Review session2
Review session2NEEDY12345
 
Interval intersection
Interval intersectionInterval intersection
Interval intersectionAabida Noman
 
Lect11 Sorting
Lect11 SortingLect11 Sorting
Lect11 Sortingryokollll
 
Chapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for printChapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for printAbdii Rashid
 
Skiena algorithm 2007 lecture05 dictionary data structure trees
Skiena algorithm 2007 lecture05 dictionary data structure treesSkiena algorithm 2007 lecture05 dictionary data structure trees
Skiena algorithm 2007 lecture05 dictionary data structure treeszukun
 
search_sort Search sortSearch sortSearch sortSearch sort
search_sort Search sortSearch sortSearch sortSearch sortsearch_sort Search sortSearch sortSearch sortSearch sort
search_sort Search sortSearch sortSearch sortSearch sortShanmuganathan C
 
Advanced data structure
Advanced data structureAdvanced data structure
Advanced data structureShakil Ahmed
 
Data structure lecture 3
Data structure lecture 3Data structure lecture 3
Data structure lecture 3Kumar
 
20121020 semi local-string_comparison_tiskin
20121020 semi local-string_comparison_tiskin20121020 semi local-string_comparison_tiskin
20121020 semi local-string_comparison_tiskinComputer Science Club
 
21 elementarysorts 2
21 elementarysorts 221 elementarysorts 2
21 elementarysorts 2Hoang Nguyen
 
Preparation Data Structures 06 arrays representation
Preparation Data Structures 06 arrays representationPreparation Data Structures 06 arrays representation
Preparation Data Structures 06 arrays representationAndres Mendez-Vazquez
 
Dsoop (co 221) 1
Dsoop (co 221) 1Dsoop (co 221) 1
Dsoop (co 221) 1Puja Koch
 

Ähnlich wie Week09 (20)

Review session2
Review session2Review session2
Review session2
 
s11_bin_search_trees.ppt
s11_bin_search_trees.ppts11_bin_search_trees.ppt
s11_bin_search_trees.ppt
 
Ch04n
Ch04nCh04n
Ch04n
 
Gwt sdm public
Gwt sdm publicGwt sdm public
Gwt sdm public
 
Interval intersection
Interval intersectionInterval intersection
Interval intersection
 
sorting.pptx
sorting.pptxsorting.pptx
sorting.pptx
 
Lect11 Sorting
Lect11 SortingLect11 Sorting
Lect11 Sorting
 
Arrays in C.pptx
Arrays in C.pptxArrays in C.pptx
Arrays in C.pptx
 
Chapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for printChapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for print
 
Skiena algorithm 2007 lecture05 dictionary data structure trees
Skiena algorithm 2007 lecture05 dictionary data structure treesSkiena algorithm 2007 lecture05 dictionary data structure trees
Skiena algorithm 2007 lecture05 dictionary data structure trees
 
Data structures
Data structuresData structures
Data structures
 
search_sort Search sortSearch sortSearch sortSearch sort
search_sort Search sortSearch sortSearch sortSearch sortsearch_sort Search sortSearch sortSearch sortSearch sort
search_sort Search sortSearch sortSearch sortSearch sort
 
Advanced data structure
Advanced data structureAdvanced data structure
Advanced data structure
 
Data structure lecture 3
Data structure lecture 3Data structure lecture 3
Data structure lecture 3
 
Chapter 4 ds
Chapter 4 dsChapter 4 ds
Chapter 4 ds
 
20121020 semi local-string_comparison_tiskin
20121020 semi local-string_comparison_tiskin20121020 semi local-string_comparison_tiskin
20121020 semi local-string_comparison_tiskin
 
DAA Notes.pdf
DAA Notes.pdfDAA Notes.pdf
DAA Notes.pdf
 
21 elementarysorts 2
21 elementarysorts 221 elementarysorts 2
21 elementarysorts 2
 
Preparation Data Structures 06 arrays representation
Preparation Data Structures 06 arrays representationPreparation Data Structures 06 arrays representation
Preparation Data Structures 06 arrays representation
 
Dsoop (co 221) 1
Dsoop (co 221) 1Dsoop (co 221) 1
Dsoop (co 221) 1
 

Mehr von hccit

Snr ipt 10_syll
Snr ipt 10_syllSnr ipt 10_syll
Snr ipt 10_syllhccit
 
Snr ipt 10_guide
Snr ipt 10_guideSnr ipt 10_guide
Snr ipt 10_guidehccit
 
3 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr123 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr12hccit
 
3 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr113 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr11hccit
 
10 ict photoshop_proj_2014
10 ict photoshop_proj_201410 ict photoshop_proj_2014
10 ict photoshop_proj_2014hccit
 
Photoshop
PhotoshopPhotoshop
Photoshophccit
 
Flash
FlashFlash
Flashhccit
 
University partnerships programs email
University partnerships programs emailUniversity partnerships programs email
University partnerships programs emailhccit
 
Griffith sciences pathway programs overview
Griffith sciences pathway programs overviewGriffith sciences pathway programs overview
Griffith sciences pathway programs overviewhccit
 
Griffith info tech brochure
Griffith info tech brochureGriffith info tech brochure
Griffith info tech brochurehccit
 
Pm sql exercises
Pm sql exercisesPm sql exercises
Pm sql exerciseshccit
 
Repairs questions
Repairs questionsRepairs questions
Repairs questionshccit
 
Movies questions
Movies questionsMovies questions
Movies questionshccit
 
Australian birds questions
Australian birds questionsAustralian birds questions
Australian birds questionshccit
 
Section b
Section bSection b
Section bhccit
 
Section a
Section aSection a
Section ahccit
 
Ask manual rev5
Ask manual rev5Ask manual rev5
Ask manual rev5hccit
 
Case study report mj
Case study report mjCase study report mj
Case study report mjhccit
 

Mehr von hccit (20)

Snr ipt 10_syll
Snr ipt 10_syllSnr ipt 10_syll
Snr ipt 10_syll
 
Snr ipt 10_guide
Snr ipt 10_guideSnr ipt 10_guide
Snr ipt 10_guide
 
3 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr123 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr12
 
3 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr113 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr11
 
10 ict photoshop_proj_2014
10 ict photoshop_proj_201410 ict photoshop_proj_2014
10 ict photoshop_proj_2014
 
Photoshop
PhotoshopPhotoshop
Photoshop
 
Flash
FlashFlash
Flash
 
University partnerships programs email
University partnerships programs emailUniversity partnerships programs email
University partnerships programs email
 
Griffith sciences pathway programs overview
Griffith sciences pathway programs overviewGriffith sciences pathway programs overview
Griffith sciences pathway programs overview
 
Griffith info tech brochure
Griffith info tech brochureGriffith info tech brochure
Griffith info tech brochure
 
Pm sql exercises
Pm sql exercisesPm sql exercises
Pm sql exercises
 
Repairs questions
Repairs questionsRepairs questions
Repairs questions
 
Movies questions
Movies questionsMovies questions
Movies questions
 
Australian birds questions
Australian birds questionsAustralian birds questions
Australian birds questions
 
Section b
Section bSection b
Section b
 
B
BB
B
 
A
AA
A
 
Section a
Section aSection a
Section a
 
Ask manual rev5
Ask manual rev5Ask manual rev5
Ask manual rev5
 
Case study report mj
Case study report mjCase study report mj
Case study report mj
 

Kürzlich hochgeladen

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 

Kürzlich hochgeladen (20)

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 

Week09

  • 2. Copyright Warning COMMONWEALTH OF AUSTRALIA Copyright Regulations 1969 WARNING This material has been copied and communicated to you by or on behalf of Bond University pursuant to Part VB of the Copyright Act 1968 (the Act). The material in this communication may be subject to copyright under the Act. Any further copying or communication of this material by you may be the subject of copyright protection under the Act. Do not remove this notice. © 2004 Pearson Addison-Wesley. All rights reserved 4-2
  • 3. Sorting Frequently, we want our collections of data sorted (in ascending order, alphabetically, etc.) There are many algorithms for sorting data Considerations: • How to compare elements? – numerically, in ascending or descending order – alphabetically – highest card, etc. • How are elements stored? – e.g., if an array, need to move elements around until they are in the right order • What is the best method? – need a way to characterise different sorting methods to decide which is best for the problem at hand © 2004 Pearson Addison-Wesley. All rights reserved 4-3
  • 4. Selection Sort Selection sort pseudo-code algorithm: problem: sort the array A into ascending order 1. Find the position of the smallest element of A 2. Swap the smallest with the element at position A[0] 3. Find the position of the smallest element of A from position 1 to the end of A 4. Swap this smallest element with the element at position A[1] 5. Find the position of the smallest element of A from position 2 to the end of A 6. Swap with A[2] 7. Repeat this process until the whole array has been sorted © 2004 Pearson Addison-Wesley. All rights reserved 4-4
  • 5. Selection Sort Example (from Phil Stocks’ slides) original array: A: 11 2 3 7 5 0 1 2 3 4 A: 11 2 3 7 5 A: 2 11 3 7 5 from 1 0 2 3 4 0 1 2 3 4 A: 2 11 3 7 5 A: 2 3 11 7 5 0 1 2 3 4 0 1 2 3 4 A: 2 3 11 7 5 A: 2 3 5 7 11 0 1 2 3 4 0 1 2 3 4 A: 2 3 5 7 11 A: 2 3 5 7 11 0 1 2 3 4 0 1 2 3 4 A: 2 3 5 7 11 A: 2 3 5 7 11 0 1 2 3 4 done 0 1 2 3 4 © 2004 Pearson Addison-Wesley. All rights reserved 4-5
  • 6. Selection Sort in Java: Stepwise Refinement // Perform a selection sort of the array A public void selSort ( int [ ] A ) { // iterate over indices up to second from the end (A.length – 2) for ( int i = 0; i < A.length – 1; i++) { // find position, k, of smallest element of remaining array: // i.e., position, k, of smallest in A[i .. A.length – 1] <need code here> // swap elements at positions i and k <need code here> } } © 2004 Pearson Addison-Wesley. All rights reserved 4-6
  • 7. Selection Sort in Java: Stepwise Refinement // Perform a selection sort of the array A public void selSort ( int [ ] A ) { // iterate over indices up to second from the end (A.length – 2) for ( int i = 0; i < A.length – 1; i++) { // find position, k, of smallest element of remaining array: // i.e., position, k, of smallest in A[i .. A.length – 1] int k; <need code here> // swap elements at positions i and k int temp = a[i]; a[i] = a[k]; a[k] = temp; } } © 2004 Pearson Addison-Wesley. All rights reserved 4-7
  • 8. Selection Sort in Java: Stepwise Refinement // Perform a selection sort of the array A public void selSort ( int [ ] A ) { // iterate over indices up to second from the end (A.length – 2) for ( int i = 0; i < A.length – 1; i++) { // find position, k, of smallest element of remaining array: // i.e., position, k, of smallest in A[i .. A.length – 1] int k = i; Note the initialisation for (int j = i+1; j < A.length; j++) to i if ( A[j] < A[k] ) k = j; // swap elements at positions i and k int temp = A[i]; A[i] = A[k]; A[k] = temp; } © 2004 Pearson Addison-Wesley. All rights reserved 4-8
  • 9. Selection Sort Analysis How good is selection sort? How fast is it? Most often executed statement: – statement body of innermost for-loop: if ( A[j] < A[k] ) k = j; How many executions of this statement for an array of length n? – first iteration of outer loop: n-1 times – second iteration of outer loop: n-2 times – … – last iteration of outer loop: 1 time ⇒ (n-1) + (n-2) + … + 2 + 1 = n (n-1) / 2 this is proportional to n2 We call selection sort an order n2 algorithm ( written: O(n2) ) © 2004 Pearson Addison-Wesley. All rights reserved 4-9
  • 10. How slow is O(n2)? Example, sort population of England, approximately 50 million n2 = 5 x 107 x 5 x 107 = 2.5 x 1015 I.e., on the order of 2.5 x 1015 comparisons executed! (At 100 million comparisons per second (optimistic) this would take nearly a year to run.) © 2004 Pearson Addison-Wesley. All rights reserved 4-10
  • 11. Searching Very common to search through collections of data looking for a particular element Again, efficiency is a realistic concern Consider Linear Search from before:How fast is it? How many boolean found = false; comparisons? for (int index=0; index<SIZE && !found; index+ For an array of length n, +) on the order of n if (A[index] == X) comparisons found = true; Linear search is order n ( O(n) ) © 2004 Pearson Addison-Wesley. All rights reserved 4-11
  • 12. Searching Ordered Data Common to keep collections in sorted order. We can use that knowledge to speed up searching Linear Search II: boolean found = false; (of sorted array) for (int index=0; index<SIZE && !found; • proceed from front to index++) { back if ( A[index] > X) • if value at position equals X then found break; • if value of position is greater than X, X if (A[index] == X) cannot be in the array, found = true; so break } Linear Search II is still order n © 2004 Pearson Addison-Wesley. All rights reserved 4-12
  • 13. Twenty Questions I’m thinking of a number between 1 and 1,000,000 Can you guess it in 20 questions? “Is it smaller than 500,000?” “yes” “Is it smaller than 250,000?” “no” “Is it smaller than 375,000?” “no” etc. Each question halves the remaining viable numbers How many questions to search 1,000,000? I.e., how many times can 1,000,000 be divided by 2? – 220 = 1, 048, 576 – log2(1,048,576) = 20 – log2(1,000,000) < 20 therefore, 20 questions is enough! © 2004 Pearson Addison-Wesley. All rights reserved 4-13
  • 14. Twenty Questions Find the value X in a sorted array A in the range A[0] to A[size]: • Start with the middle element. If X > A[middle], search the top half. If X < A[middle], search the bottom half. In either case, now searching a subarray half the original size. • The search continues by checking the middle element of the subarray and further halving the search space. • End when find a location P in 0..Size such that A[P-1] < X <= A[P]. If the current position is at one end then X < A[0] or X > A[Size] A Find 27: -5 2 5 9 13 14 27 31 44 51 -5 2 5 9 13 14 27 31 44 51 -5 2 5 9 13 14 27 31 44 51 © 2004 Pearson Addison-Wesley. All rights reserved 4-14
  • 15. Binary Search Procedure int binSearch ( int [ ] A, int x) // return index of x in A { int left = 0; right = A.length-1; mid; if (A.length == 0 || x < A[0]) return –1; if ( x > A[right] ) return A.length; while (left < right) { // assertion: A[left]< x < A[right] mid = (left + right) / 2 ; if ( x == A[mid] ) return (x); if (x < A[mid] ) right = mid - 1; else left = mid + 1; } if (x == A[left]) return left; else return –1; © 2004 Pearson Addison-Wesley. All rights reserved 4-15 }