Unit 10 - Algorithms

download Unit 10 - Algorithms

of 47

Transcript of Unit 10 - Algorithms

  • 8/13/2019 Unit 10 - Algorithms

    1/47

    Algorithms:

    Searching & SortingUnit 10

  • 8/13/2019 Unit 10 - Algorithms

    2/47

    How would you searchthrough a shuffled deck for the

    Queen of Hearts?

  • 8/13/2019 Unit 10 - Algorithms

    3/47

    How do you look up a numberin a phone book?

  • 8/13/2019 Unit 10 - Algorithms

    4/47

    Algorithms

    A sequence of steps to solve a problem

    Chocolate Chip Cookie Recipe

    Driving directions

    Finding the min/max

    Searching & Sorting

  • 8/13/2019 Unit 10 - Algorithms

    5/47

    Search A Collection For

    The location of a key value

    The existence of a key value

  • 8/13/2019 Unit 10 - Algorithms

    6/47

    Linear Search Also known as sequential search

    Search through list from beginning tiltarget value is found or end is reached

    No specific order of values is required

    Max comparisons: N (size of list)

  • 8/13/2019 Unit 10 - Algorithms

    7/47

    Linear Search

    public static int linearSearch(int[] numbers, int key){

    for (int x = 0; x < numbers.length; x++){

    if (numbers[x] == key)return x;

    }return -1;

    }

    Exit loop AND methodonce match found

    If still in method after allelements checked, no match

  • 8/13/2019 Unit 10 - Algorithms

    8/47

    Binary Search

    While target value not found and not done

    Find middle value of remaining list area

    Match? Search is done

    Target < middle?Continue left of middle

    Target > middle?Continue right of middle

  • 8/13/2019 Unit 10 - Algorithms

    9/47

    Binary Searchpublic static int binarySearch(int[] numbers, int key)

    { int low = 0;int high = numbers.length - 1;while (low

  • 8/13/2019 Unit 10 - Algorithms

    10/47

    Binary SearchRequires that the list be in order

    To calculate max comparisons for list of size N:

    Find lowest power of 2 that N is less than

    That power is the maximum comparisons

  • 8/13/2019 Unit 10 - Algorithms

    11/47

    Binary Search

    Examples of calculating max comparisons:

    N = 55 32 (2 5)

  • 8/13/2019 Unit 10 - Algorithms

    12/47

    Search Comparison

    o

    Tme

    Size

    Linear

    inary

  • 8/13/2019 Unit 10 - Algorithms

    13/47

    Sorting

    Arrange elements of a list in order

    Promotes more efficient searching

    Sorting Algorithms we will study

    Selection Sort

    Insertion SortBubble Sort(not on AP exam)

    Merge Sort (next unit)

  • 8/13/2019 Unit 10 - Algorithms

    14/47

    Sort by Increasing Size

  • 8/13/2019 Unit 10 - Algorithms

    15/47

    Selection Sort

    For each location

    Search list from this location to the end for

    smallest (or largest if descending) value

    Swap into this location

  • 8/13/2019 Unit 10 - Algorithms

    16/47

    58 79 14 23 94 90 66 75

    Selection Sort

    14 79 58 23 94 90 66 75min i imin i i i i i

    5814

    min imin i i i i imin

    7923

    14 23 58 79 94 90 66 75

    i i i i imin

    58

  • 8/13/2019 Unit 10 - Algorithms

    17/47

    Selection Sort

    14 23 58 79 94 90 66 757966

    14 23 58 66 94 90 79 75 9475

    14 23 58 66 75 90 79 949079

    14 23 58 66 75 79 90 9490

  • 8/13/2019 Unit 10 - Algorithms

    18/47

    Selection Sort

    Makes N-1 passes (N is size of list)

    Makes same number of comparisons evenif list is already in order or in reverse order!

  • 8/13/2019 Unit 10 - Algorithms

    19/47

    public static void selectionSort(int[] numbers){

    int length = numbers.length;for (int start = 0; start < length-1; start++){

    int minIndex = start;for (int i = start + 1; i < length; i++){

    if (numbers[i] < numbers[minIndex])minIndex = i;

    }

    int temp = numbers[start];numbers[start] = numbers[minIndex];numbers[minIndex] = temp;

    }}

    N-1 Passes

    Find smallestone remaining

    Swap into place

  • 8/13/2019 Unit 10 - Algorithms

    20/47

    MeatLoafStyxBoston

    Sort Alphabetically

    Wings

    BostonWingsMeat

    LoafStyx

  • 8/13/2019 Unit 10 - Algorithms

    21/47

    Insertion Sort

    For each element starting at 2nd element

    Keep searching for insertion point whilevalue is smaller than elements in front of it

    Insert element at insertion point

  • 8/13/2019 Unit 10 - Algorithms

    22/47

    58 79 14 23 94 90 66 75

    Insertion Sort

    pos - 1

    79Key

    58 79 14 23 94 90 66 75

    pos - 1

    14Key

    pos - 1

    795814

    14 58 79 23 94 90 66 75

    pos - 1

    23Key

    pos - 1

    795823

    pos - 1

  • 8/13/2019 Unit 10 - Algorithms

    23/47

    Insertion Sort

    14 23 58 79 94 90 66 75

    14 23 58 79 94 90 66 7594

    14 23 58 79 90 94 66 759490

    14 23 58 66 79 90 94 75 94

    90

    7966

    907975

    94Key

    90Key

    66Key75Key

  • 8/13/2019 Unit 10 - Algorithms

    24/47

    Insertion Sort

    Makes N-1 passes (N is size of list)

    Makes only N-1 comparisons ifalready in order

    Max work load if in reverse order

  • 8/13/2019 Unit 10 - Algorithms

    25/47

    public static void insertionSort(int[] numbers){

    int len = numbers.length;for (int index = 1; index < len; index++){

    int key = numbers[index];int position = index;

    while (position > 0&& key < numbers[position-1]){

    numbers[position] = numbers[position-1];position--;

    }numbers[position] = key;

    }}

    N-1 Passes

    Search forinsertion point

    No iterationsif key > valuein front of it

  • 8/13/2019 Unit 10 - Algorithms

    26/47

    Sort byIncreasing Size

    End of Pass 1

    Is this pair inincreasing order?If not, swap them.

  • 8/13/2019 Unit 10 - Algorithms

    27/47

    Sort byIncreasing Size

    End of Pass 2

    Is this pair inincreasing order?If not, swap them.

  • 8/13/2019 Unit 10 - Algorithms

    28/47

    Sort byIncreasing Size

    End of Pass 3

    Is this pair inincreasing order?If not, swap them.

  • 8/13/2019 Unit 10 - Algorithms

    29/47

    Sort byIncreasing Size

    EndMax of 4 Passes

    Is this pair inincreasing order?If not, swap them.

  • 8/13/2019 Unit 10 - Algorithms

    30/47

    Bubble Sort

    For each location in the list (except last)and while swaps are being made

    Traverse listCompare element with neighbor

    If elements are out of order, swap themNext largest value has sunk into place

  • 8/13/2019 Unit 10 - Algorithms

    31/47

    58 79 14 23 94 90 66 75

    Bubble Sort

    7914 23 79 90 94 94 9466 75

    58 14 23 79 90 66 75 9414 9058 58 9066 7523

    14 23 58 79 66 75 90 947966 7975

  • 8/13/2019 Unit 10 - Algorithms

    32/47

    Bubble Sort

    14 23 58 66 75 79 90 94

    Did we makeany swaps?

    No swaps?Were done!

  • 8/13/2019 Unit 10 - Algorithms

    33/47

  • 8/13/2019 Unit 10 - Algorithms

    34/47

    public static void bubbleSort(int[] numbers){

    int bottom = numbers.length - 1;boolean swapped = true;while (swapped){

    swapped = false;for (int i = 0; i < bottom; i++){

    if (numbers[i] > numbers[i+1]){

    int temp = numbers[i];numbers[i] = numbers[i+1];numbers[i+1] = temp;

    swapped = true;}

    }bottom--;

    }

    }

    Stop when noswaps made

    or bottom == 0

    Swap out oforder neighbors

    Next largestnow in place

  • 8/13/2019 Unit 10 - Algorithms

    35/47

    Practice Interactively

    On myPISD, go to APCS1 Class Resources

    Choose Algorithm Animation Websites

  • 8/13/2019 Unit 10 - Algorithms

    36/47

    Sorting In-order Arrays

    Sort# of

    PassesComparisons

    Per PassTotal

    Comparisons

    Selection n 1 n / 2 (n 1) (n / 2)

    Insertion n 1 1 n 1Bubble 1 n 1 n 1

  • 8/13/2019 Unit 10 - Algorithms

    37/47

    Insert/Delete an Item

    ArrayList provides ability to insert into anordered list and delete from a list with ease

    Java array does not!

    Insert into ordered list assumingsufficient space is always successful

    Delete from list not always successful

  • 8/13/2019 Unit 10 - Algorithms

    38/47

    0

    Inserting 40 into Sorted Array

    20 35 6550 80 80655040 0

    End of Array

    End of Array

    40 < 80Slide 80 over

    40 < 65Slide 65 over

    40 < 50Slide 50 over

    40 > 35Insert 40

    Move logicalend of array

  • 8/13/2019 Unit 10 - Algorithms

    39/47

    Inserting Into Sorted Java Array

    Working backwards from next availableindex until insertion point found

    If item to insert is less than element to left,

    shift element to current location

    Otherwise, insertion point found

    Store insertion item at insertion point

    Increase number of elements counter

  • 8/13/2019 Unit 10 - Algorithms

    40/47

    Insertion Solution

    public void insert(int value){

    int index = numInArray;while (index > 0

    && value < numbers[index-1]){

    numbers[index] = numbers[index-1];index--;

    }numbers[index] = value;numInArray++;

    }

    Shift items to rightuntil insertion

    point found

    Insert the item

  • 8/13/2019 Unit 10 - Algorithms

    41/47

    80

    Deleting 40 From Array

    20 35 5040 65806550 0

    End of Array

    End of Array

    Find the 40

    Slide 50 over totake its place

    Slide 65 over

    Slide 80 over

    Move logical

    end of array

  • 8/13/2019 Unit 10 - Algorithms

    42/47

    Deleting From Java Array

    Search for item to delete

    If found, traverse array frommatch location to end

    Shift each element to left

    Reduce number of elements count

  • 8/13/2019 Unit 10 - Algorithms

    43/47

    Deletion Solutionpublic boolean delete(int value){

    int index = 0;boolean found = false;while (!found && index < numInArray){

    if (numbers[index] == value)found = true;

    elseindex++;

    }if (found)

    { for (int k = index; k < numInArray-1; k++)numbers[k] = numbers[k+1]; // shift to left

    numInArray--;}

    return found;}

    Search for value

    to delete

    Slide over remainingelements to take its place

  • 8/13/2019 Unit 10 - Algorithms

    44/47

    Deletion Solutionpublic boolean delete(int value){

    int index = Arrays.binarySearch(numbers, 0, numInArray,value);

    if (index >= 0){

    while (index < numInArray - 1)

    {numbers[index] = numbers[index + 1];index++;

    }numInArray--;

    return true;}else{

    return false;}

    }

    Search for valueto delete

    If not found, method returns[ -(insertion index) 1]

  • 8/13/2019 Unit 10 - Algorithms

    45/47

    Searching/Sorting with Arrays of Objects

    Comparing is different

    Primitives : == , > , >= , < ,

  • 8/13/2019 Unit 10 - Algorithms

    46/47

    Searching/Sorting with Arrays of Objects

    Compare entire object if Comparable interface implemented ( compareTo )

    if (list[x].compareTo(list[y]) < 0)

    Can also compare object fields

    if (list[x].value() < list[y].value())

  • 8/13/2019 Unit 10 - Algorithms

    47/47

    Helpful Utility Libraries

    java.util.Arrays

    java.util.Collections

    String toString( ____ [ ] arr)

    void sort( ____ [ ] arr)

    int binarySearch( ____ [ ] arr, ___ key)

    Object or anyprimitive type ( int ,

    double , etc.)

    int binarySearch(List list, T key)

    void sort(List list)