SlideShare ist ein Scribd-Unternehmen logo
1 von 26
Algorithms & Data Structures CS112
                          Spring 2012
                            Lecture 4


                Syed Muhammad Raza
Searching Algorithms
   Searching is the process of determining whether or not a given value
    exists in a data structure or a storage media.

   We will study two searching algorithms

       Linear Search

       Binary Search
Linear Search: O(n)
   The linear (or sequential) search algorithm on an array is:

       Start from beginning of an array/list and continues until the item is
        found or the entire array/list has been searched.

       Sequentially scan the array, comparing each array item with the
        searched value.

       If a match is found; return the index of the matched element;
        otherwise return –1.

   Note: linear search can be applied to both sorted and unsorted
    arrays.
Linear Search
     bool LinSearch(double x[ ], int n, double item)
     {
             for(int i=0;i<n;i++)
             {
                 if(x[i]==item)
                 {
                        return true;
                 }
                 else
                 {
                         return false;
                 }
             }
             return false;
         }
Linear Search Tradeoffs
   Benefits
       Easy to understand
       Array can be in any order
   Disadvantages
       Inefficient for array of N elements
        Examines N/2 elements on average for value in array, N
        elements for value not in array
Binary Search: O(log2 n)
   Binary search looks for an item in an array/list using
    divide and conquer strategy
Binary Search
    Binary search algorithm assumes that the items in the array being
     searched is sorted

    The algorithm begins at the middle of the array in a binary
     search

    If the item for which we are searching is less than the item in the
     middle, we know that the item won’t be in the second half of the
     array

    Once again we examine the “middle” element

    The process continues with each comparison cutting in half the
     portion of the array where the item might be
Binary Search
   Binary search uses a recursive method to search an array to find a
    specified value

   The array must be a sorted array:

    a[0]≤a[1]≤a[2]≤. . . ≤ a[finalIndex]

   If the value is found, its index is returned

   If the value is not found, -1 is returned

   Note: Each execution of the recursive method reduces the search
    space by about a half
Pseudocode for Binary Search
Execution of Binary Search
Execution of Binary Search
Key Points in Binary Search
1.       There is no infinite recursion
     •      On each recursive call, the value of first is increased, or the
            value of last is decreased
     •      If the chain of recursive calls does not end in some other way,
            then eventually the method will be called with first larger than
            last

2.       Each stopping case performs the correct action for that case
     •      If first > last, there are no array elements between a[first] and
            a[last], so key is not in this segment of the array, and result is
            correctly set to -1
     •      If key == a[mid], result is correctly set to mid
Key Points in Binary Search
3.       For each of the cases that involve recursion, if all recursive calls
         perform their actions correctly, then the entire case performs
         correctly

     •      If key < a[mid], then key must be one of the elements a[first]
            through a[mid-1], or it is not in the array

     •      The method should then search only those elements, which it
            does

     •      The recursive call is correct, therefore the entire action is
            correct
Key Points in Binary Search
    •    If key > a[mid], then key must be one of the elements
         a[mid+1] through a[last], or it is not in the array

    •    The method should then search only those elements, which it
         does

    •    The recursive call is correct, therefore the entire action is
         correct

The method search passes all three tests:

Therefore, it is a good recursive method definition
Efficiency of Binary Search
   The binary search algorithm is extremely fast compared to an
    algorithm that tries all array elements in order

       About half the array is eliminated from consideration right at the
        start

       Then a quarter of the array, then an eighth of the array, and so
        forth
Efficiency of Binary Search
   Given an array with 1,000 elements, the binary search will only need
    to compare about 10 array elements to the key value, as compared
    to an average of 500 for a serial search algorithm

   The binary search algorithm has a worst-case running time that is
    logarithmic:   O(log n)

       A serial search algorithm is linear: O(n)

   If desired, the recursive version of the method search can be
    converted to an iterative version that will run more efficiently
Binary Search
Algorithms & Data Structures CSC-112
                              Fall 2011
                              Lecture 5



                Syed Muhammad Raza
Sorting Algorithms
   Sorting is the process of rearranging your data elements/Item in
    ascending or descending order
       Unsorted Data

                  4     3         2   7   1   6   5   8    9


       Sorted Data (Ascending)

                  1     2         3   4   5   6   7   8    9


       Sorted Data (Descending)


                  9     8         7   6   5   4   3   2    1
Sorting Algorithms
   They are many
       Bubble Sort
       Selection Sort
       Insertion Sort
       Shell sort
       Comb Sort
       Merge Sort
       Heap Sort
       Quick Sort
       Counting Sort
       Bucket Sort
       Radix Sort
       Distribution Sort
       Time Sort
                            Source: Wikipedia
Bubble Sort
   Compares Adjacent Items and Exchanges Them if They are Out of
    Order

   When You Order Successive Pairs of Elements, the Largest Element
    Bubbles to the Top(end) of the Array

   Bubble Sort (Usually) Requires Several Passes Through the Array
Bubble Sort

          Pass 1                       Pass 2

29   10    14      37   13   10   14     29     13   37

10   29    14      37   13   10   14     29     13   37

10   14    29      37   13   10   14     29     13   37

10   14    29      37   13   10   14     13     29   37

10   14    29      13   37
Selection Sort
   To Sort an Array into Ascending Order, First Search for the Largest Element

   Because You Want the Largest Element to be in the Last Position of the
    Array, You Swap the Last Item With the Largest Item to be in the Last Position of
    the Array, You Swap the Last Item with the Largest Item, Even if These Items
    Appear to be Identical

   Now, Ignoring the Last (Largest) Item of the Array, search Rest of the Array For
    Its Largest Item and Swap it With Its Last Item, Which is the Next-to-Last Item in
    the original Array

   You Continue Until You Have Selected and Swapped N-1 of the N Items in the
    Array

   The Remaining Item, Which is Now in the First Position of the Array, is in its
    Proper Order
Selection Sort



       Initial Array   29   10   14   37   13

      After1st Swap    29   10   14   13   37

      After2nd Swap    13   10   14   29   37

      After3rd Swap    13   10   14   29   37

      After4th Swap    10   13   14   29   37
Insertion Sort
   Divide Array Into Sorted Section At Front (Initially Empty), Unsorted
    Section At End

   Step Iteratively Through Array, Moving Each Element To Proper
    Place In Sorted Section

                     Sorted                           Unsorted


                  …..                                    …..

           0                           i                          N-1
                                After i Iterations
Insertion Sort

Initial Array   29   10   14   37   13      Copy 10

                29   29   14   37   13      Shift 29

                10   29   14   37   13   Insert 10, Copy 14


                10   29   29   37   13      Shift 29

                                         Insert 14; Copy 37
                10   14   29   37   13
                                         Insert 37 on Itself

                10   14   29   37   13      Copy 13

                10   14   14   29   37   Shift 14, 29, 37


Sorted Array    10   13   14   29   37       Insert 13

Weitere ähnliche Inhalte

Was ist angesagt?

Searching & Sorting Algorithms
Searching & Sorting AlgorithmsSearching & Sorting Algorithms
Searching & Sorting AlgorithmsRahul Jamwal
 
Lecture 3 data structures & algorithms - sorting techniques - http://techiem...
Lecture 3  data structures & algorithms - sorting techniques - http://techiem...Lecture 3  data structures & algorithms - sorting techniques - http://techiem...
Lecture 3 data structures & algorithms - sorting techniques - http://techiem...Dharmendra Prasad
 
Sorting Seminar Presentation by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha MajumderSorting Seminar Presentation by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha MajumderAshin Guha Majumder
 
Lect11 Sorting
Lect11 SortingLect11 Sorting
Lect11 Sortingryokollll
 
Searching Sorting
Searching SortingSearching Sorting
Searching Sortingguest2cb109
 
sorting algorithm graphical method
sorting algorithm graphical method sorting algorithm graphical method
sorting algorithm graphical method Shantanu Mishra
 
Hub 102 - Lesson 5 - Algorithm: Sorting & Searching
Hub 102 - Lesson 5 - Algorithm: Sorting & SearchingHub 102 - Lesson 5 - Algorithm: Sorting & Searching
Hub 102 - Lesson 5 - Algorithm: Sorting & SearchingTiểu Hổ
 
Rahat &amp; juhith
Rahat &amp; juhithRahat &amp; juhith
Rahat &amp; juhithRj Juhith
 
Coin Changing, Binary Search , Linear Search - Algorithm
Coin Changing, Binary Search , Linear Search - AlgorithmCoin Changing, Binary Search , Linear Search - Algorithm
Coin Changing, Binary Search , Linear Search - AlgorithmMd Sadequl Islam
 
Sorting & Linked Lists
Sorting & Linked ListsSorting & Linked Lists
Sorting & Linked ListsJ.T.A.JONES
 
Algorithms Lecture 6: Searching Algorithms
Algorithms Lecture 6: Searching AlgorithmsAlgorithms Lecture 6: Searching Algorithms
Algorithms Lecture 6: Searching AlgorithmsMohamed Loey
 
(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sorting(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sortingFadhil Ismail
 
Insertion Sort, Quick Sort And Their complexity
Insertion Sort, Quick Sort And Their complexityInsertion Sort, Quick Sort And Their complexity
Insertion Sort, Quick Sort And Their complexityMotaleb Hossen Manik
 
Dsa – data structure and algorithms searching
Dsa – data structure and algorithms   searchingDsa – data structure and algorithms   searching
Dsa – data structure and algorithms searchingsajinis3
 

Was ist angesagt? (20)

Searching & Sorting Algorithms
Searching & Sorting AlgorithmsSearching & Sorting Algorithms
Searching & Sorting Algorithms
 
Lecture 3 data structures & algorithms - sorting techniques - http://techiem...
Lecture 3  data structures & algorithms - sorting techniques - http://techiem...Lecture 3  data structures & algorithms - sorting techniques - http://techiem...
Lecture 3 data structures & algorithms - sorting techniques - http://techiem...
 
Sorting Seminar Presentation by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha MajumderSorting Seminar Presentation by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha Majumder
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
 
Sorting
SortingSorting
Sorting
 
Lect11 Sorting
Lect11 SortingLect11 Sorting
Lect11 Sorting
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Searching Sorting
Searching SortingSearching Sorting
Searching Sorting
 
sorting algorithm graphical method
sorting algorithm graphical method sorting algorithm graphical method
sorting algorithm graphical method
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Hub 102 - Lesson 5 - Algorithm: Sorting & Searching
Hub 102 - Lesson 5 - Algorithm: Sorting & SearchingHub 102 - Lesson 5 - Algorithm: Sorting & Searching
Hub 102 - Lesson 5 - Algorithm: Sorting & Searching
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Rahat &amp; juhith
Rahat &amp; juhithRahat &amp; juhith
Rahat &amp; juhith
 
Coin Changing, Binary Search , Linear Search - Algorithm
Coin Changing, Binary Search , Linear Search - AlgorithmCoin Changing, Binary Search , Linear Search - Algorithm
Coin Changing, Binary Search , Linear Search - Algorithm
 
Binary search
Binary searchBinary search
Binary search
 
Sorting & Linked Lists
Sorting & Linked ListsSorting & Linked Lists
Sorting & Linked Lists
 
Algorithms Lecture 6: Searching Algorithms
Algorithms Lecture 6: Searching AlgorithmsAlgorithms Lecture 6: Searching Algorithms
Algorithms Lecture 6: Searching Algorithms
 
(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sorting(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sorting
 
Insertion Sort, Quick Sort And Their complexity
Insertion Sort, Quick Sort And Their complexityInsertion Sort, Quick Sort And Their complexity
Insertion Sort, Quick Sort And Their complexity
 
Dsa – data structure and algorithms searching
Dsa – data structure and algorithms   searchingDsa – data structure and algorithms   searching
Dsa – data structure and algorithms searching
 

Ähnlich wie Algorithm & data structures lec4&5

advanced searching and sorting.pdf
advanced searching and sorting.pdfadvanced searching and sorting.pdf
advanced searching and sorting.pdfharamaya university
 
DS - Unit 2 FINAL (2).pptx
DS - Unit 2 FINAL (2).pptxDS - Unit 2 FINAL (2).pptx
DS - Unit 2 FINAL (2).pptxprakashvs7
 
Data Structures_ Sorting & Searching
Data Structures_ Sorting & SearchingData Structures_ Sorting & Searching
Data Structures_ Sorting & SearchingThenmozhiK5
 
Algorithm 8th lecture linear & binary search(2).pptx
Algorithm 8th lecture linear & binary search(2).pptxAlgorithm 8th lecture linear & binary search(2).pptx
Algorithm 8th lecture linear & binary search(2).pptxAftabali702240
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingEduardo Bergavera
 
MODULE 5-Searching and-sorting
MODULE 5-Searching and-sortingMODULE 5-Searching and-sorting
MODULE 5-Searching and-sortingnikshaikh786
 
Sorting algorithums > Data Structures & Algorithums
Sorting algorithums  > Data Structures & AlgorithumsSorting algorithums  > Data Structures & Algorithums
Sorting algorithums > Data Structures & AlgorithumsAin-ul-Moiz Khawaja
 
data_structure_Chapter two_computer.pptx
data_structure_Chapter two_computer.pptxdata_structure_Chapter two_computer.pptx
data_structure_Chapter two_computer.pptxMohammed472103
 
Data operatons & searching and sorting algorithms
Data operatons & searching and sorting algorithmsData operatons & searching and sorting algorithms
Data operatons & searching and sorting algorithmsAnushdika Jeganathan
 
Selection sort
Selection sortSelection sort
Selection sortasra khan
 
Binary search Algorithm
Binary search AlgorithmBinary search Algorithm
Binary search AlgorithmFazalRehman79
 

Ähnlich wie Algorithm & data structures lec4&5 (20)

advanced searching and sorting.pdf
advanced searching and sorting.pdfadvanced searching and sorting.pdf
advanced searching and sorting.pdf
 
Unit vii sorting
Unit   vii sorting Unit   vii sorting
Unit vii sorting
 
Unit 7 sorting
Unit   7 sortingUnit   7 sorting
Unit 7 sorting
 
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
 
Lecture_Oct26.pptx
Lecture_Oct26.pptxLecture_Oct26.pptx
Lecture_Oct26.pptx
 
Analysis of Algorithm - Binary Search.pptx
Analysis of Algorithm - Binary Search.pptxAnalysis of Algorithm - Binary Search.pptx
Analysis of Algorithm - Binary Search.pptx
 
Algorithm 8th lecture linear & binary search(2).pptx
Algorithm 8th lecture linear & binary search(2).pptxAlgorithm 8th lecture linear & binary search(2).pptx
Algorithm 8th lecture linear & binary search(2).pptx
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and Searching
 
Sorting
SortingSorting
Sorting
 
MODULE 5-Searching and-sorting
MODULE 5-Searching and-sortingMODULE 5-Searching and-sorting
MODULE 5-Searching and-sorting
 
Unit 6 dsa SEARCHING AND SORTING
Unit 6 dsa SEARCHING AND SORTINGUnit 6 dsa SEARCHING AND SORTING
Unit 6 dsa SEARCHING AND SORTING
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
search_sort.ppt
search_sort.pptsearch_sort.ppt
search_sort.ppt
 
Sorting algorithums > Data Structures & Algorithums
Sorting algorithums  > Data Structures & AlgorithumsSorting algorithums  > Data Structures & Algorithums
Sorting algorithums > Data Structures & Algorithums
 
Unit v data structure-converted
Unit  v data structure-convertedUnit  v data structure-converted
Unit v data structure-converted
 
data_structure_Chapter two_computer.pptx
data_structure_Chapter two_computer.pptxdata_structure_Chapter two_computer.pptx
data_structure_Chapter two_computer.pptx
 
Data operatons & searching and sorting algorithms
Data operatons & searching and sorting algorithmsData operatons & searching and sorting algorithms
Data operatons & searching and sorting algorithms
 
Selection sort
Selection sortSelection sort
Selection sort
 
Binary search Algorithm
Binary search AlgorithmBinary search Algorithm
Binary search Algorithm
 

Mehr von Abdul Khan

Lec 04 intro assembly
Lec 04 intro assemblyLec 04 intro assembly
Lec 04 intro assemblyAbdul Khan
 
Algorithm & data structure lec2
Algorithm & data structure lec2Algorithm & data structure lec2
Algorithm & data structure lec2Abdul Khan
 
Algorithm & data structures lec1
Algorithm & data structures lec1Algorithm & data structures lec1
Algorithm & data structures lec1Abdul Khan
 
Lec 03 ia32 architecture
Lec 03  ia32 architectureLec 03  ia32 architecture
Lec 03 ia32 architectureAbdul Khan
 
Lec 02 data representation part 2
Lec 02 data representation part 2Lec 02 data representation part 2
Lec 02 data representation part 2Abdul Khan
 
Lec 02 data representation part 1
Lec 02 data representation part 1Lec 02 data representation part 1
Lec 02 data representation part 1Abdul Khan
 
Lec 01 basic concepts
Lec 01 basic conceptsLec 01 basic concepts
Lec 01 basic conceptsAbdul Khan
 
war on terror
 war on terror war on terror
war on terrorAbdul Khan
 

Mehr von Abdul Khan (9)

Lec 04 intro assembly
Lec 04 intro assemblyLec 04 intro assembly
Lec 04 intro assembly
 
Algorithm & data structure lec2
Algorithm & data structure lec2Algorithm & data structure lec2
Algorithm & data structure lec2
 
Algorithm & data structures lec1
Algorithm & data structures lec1Algorithm & data structures lec1
Algorithm & data structures lec1
 
Lec 03 ia32 architecture
Lec 03  ia32 architectureLec 03  ia32 architecture
Lec 03 ia32 architecture
 
Lec 02 data representation part 2
Lec 02 data representation part 2Lec 02 data representation part 2
Lec 02 data representation part 2
 
Lec 02 data representation part 1
Lec 02 data representation part 1Lec 02 data representation part 1
Lec 02 data representation part 1
 
Lec 01 basic concepts
Lec 01 basic conceptsLec 01 basic concepts
Lec 01 basic concepts
 
war on terror
 war on terror war on terror
war on terror
 
Xhtml
XhtmlXhtml
Xhtml
 

Kürzlich hochgeladen

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
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
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
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
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 

Kürzlich hochgeladen (20)

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
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
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
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
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 

Algorithm & data structures lec4&5

  • 1. Algorithms & Data Structures CS112 Spring 2012 Lecture 4 Syed Muhammad Raza
  • 2. Searching Algorithms  Searching is the process of determining whether or not a given value exists in a data structure or a storage media.  We will study two searching algorithms  Linear Search  Binary Search
  • 3. Linear Search: O(n)  The linear (or sequential) search algorithm on an array is:  Start from beginning of an array/list and continues until the item is found or the entire array/list has been searched.  Sequentially scan the array, comparing each array item with the searched value.  If a match is found; return the index of the matched element; otherwise return –1.  Note: linear search can be applied to both sorted and unsorted arrays.
  • 4. Linear Search bool LinSearch(double x[ ], int n, double item) { for(int i=0;i<n;i++) { if(x[i]==item) { return true; } else { return false; } } return false; }
  • 5. Linear Search Tradeoffs  Benefits  Easy to understand  Array can be in any order  Disadvantages  Inefficient for array of N elements Examines N/2 elements on average for value in array, N elements for value not in array
  • 6. Binary Search: O(log2 n)  Binary search looks for an item in an array/list using divide and conquer strategy
  • 7. Binary Search  Binary search algorithm assumes that the items in the array being searched is sorted  The algorithm begins at the middle of the array in a binary search  If the item for which we are searching is less than the item in the middle, we know that the item won’t be in the second half of the array  Once again we examine the “middle” element  The process continues with each comparison cutting in half the portion of the array where the item might be
  • 8. Binary Search  Binary search uses a recursive method to search an array to find a specified value  The array must be a sorted array: a[0]≤a[1]≤a[2]≤. . . ≤ a[finalIndex]  If the value is found, its index is returned  If the value is not found, -1 is returned  Note: Each execution of the recursive method reduces the search space by about a half
  • 12. Key Points in Binary Search 1. There is no infinite recursion • On each recursive call, the value of first is increased, or the value of last is decreased • If the chain of recursive calls does not end in some other way, then eventually the method will be called with first larger than last 2. Each stopping case performs the correct action for that case • If first > last, there are no array elements between a[first] and a[last], so key is not in this segment of the array, and result is correctly set to -1 • If key == a[mid], result is correctly set to mid
  • 13. Key Points in Binary Search 3. For each of the cases that involve recursion, if all recursive calls perform their actions correctly, then the entire case performs correctly • If key < a[mid], then key must be one of the elements a[first] through a[mid-1], or it is not in the array • The method should then search only those elements, which it does • The recursive call is correct, therefore the entire action is correct
  • 14. Key Points in Binary Search • If key > a[mid], then key must be one of the elements a[mid+1] through a[last], or it is not in the array • The method should then search only those elements, which it does • The recursive call is correct, therefore the entire action is correct The method search passes all three tests: Therefore, it is a good recursive method definition
  • 15. Efficiency of Binary Search  The binary search algorithm is extremely fast compared to an algorithm that tries all array elements in order  About half the array is eliminated from consideration right at the start  Then a quarter of the array, then an eighth of the array, and so forth
  • 16. Efficiency of Binary Search  Given an array with 1,000 elements, the binary search will only need to compare about 10 array elements to the key value, as compared to an average of 500 for a serial search algorithm  The binary search algorithm has a worst-case running time that is logarithmic: O(log n)  A serial search algorithm is linear: O(n)  If desired, the recursive version of the method search can be converted to an iterative version that will run more efficiently
  • 18. Algorithms & Data Structures CSC-112 Fall 2011 Lecture 5 Syed Muhammad Raza
  • 19. Sorting Algorithms  Sorting is the process of rearranging your data elements/Item in ascending or descending order  Unsorted Data 4 3 2 7 1 6 5 8 9  Sorted Data (Ascending) 1 2 3 4 5 6 7 8 9  Sorted Data (Descending) 9 8 7 6 5 4 3 2 1
  • 20. Sorting Algorithms  They are many  Bubble Sort  Selection Sort  Insertion Sort  Shell sort  Comb Sort  Merge Sort  Heap Sort  Quick Sort  Counting Sort  Bucket Sort  Radix Sort  Distribution Sort  Time Sort Source: Wikipedia
  • 21. Bubble Sort  Compares Adjacent Items and Exchanges Them if They are Out of Order  When You Order Successive Pairs of Elements, the Largest Element Bubbles to the Top(end) of the Array  Bubble Sort (Usually) Requires Several Passes Through the Array
  • 22. Bubble Sort Pass 1 Pass 2 29 10 14 37 13 10 14 29 13 37 10 29 14 37 13 10 14 29 13 37 10 14 29 37 13 10 14 29 13 37 10 14 29 37 13 10 14 13 29 37 10 14 29 13 37
  • 23. Selection Sort  To Sort an Array into Ascending Order, First Search for the Largest Element  Because You Want the Largest Element to be in the Last Position of the Array, You Swap the Last Item With the Largest Item to be in the Last Position of the Array, You Swap the Last Item with the Largest Item, Even if These Items Appear to be Identical  Now, Ignoring the Last (Largest) Item of the Array, search Rest of the Array For Its Largest Item and Swap it With Its Last Item, Which is the Next-to-Last Item in the original Array  You Continue Until You Have Selected and Swapped N-1 of the N Items in the Array  The Remaining Item, Which is Now in the First Position of the Array, is in its Proper Order
  • 24. Selection Sort Initial Array 29 10 14 37 13 After1st Swap 29 10 14 13 37 After2nd Swap 13 10 14 29 37 After3rd Swap 13 10 14 29 37 After4th Swap 10 13 14 29 37
  • 25. Insertion Sort  Divide Array Into Sorted Section At Front (Initially Empty), Unsorted Section At End  Step Iteratively Through Array, Moving Each Element To Proper Place In Sorted Section Sorted Unsorted ….. ….. 0 i N-1 After i Iterations
  • 26. Insertion Sort Initial Array 29 10 14 37 13 Copy 10 29 29 14 37 13 Shift 29 10 29 14 37 13 Insert 10, Copy 14 10 29 29 37 13 Shift 29 Insert 14; Copy 37 10 14 29 37 13 Insert 37 on Itself 10 14 29 37 13 Copy 13 10 14 14 29 37 Shift 14, 29, 37 Sorted Array 10 13 14 29 37 Insert 13