Algorithms

Cards (7)

  • Counting is one of the simplest algorithms to understand
    • Algorithm to count from 1 to 10
    • FOR i ← 1 TO 10
    • OUTPUT i
    • Output: 1 2 3 4 5 6 7 8 9 10
    • Algorithm to count in twos (even numbers only)
    • FOR i ← 2 TO 10 STEP 2
    • OUTPUT i
    • Output: 2 4 6 8 10
    • When we count, we need a variable to store the counter in. This is called the iterator
  • Average algorithm
    For a sushi conveyor, how could you find the average price of the items on the conveyor?
    Total ← 0
    Count ← 0
    WHILE SushiDetected
    Count ← Count + 1
    Total ← Total + Price
    ENDWHILE
    Average ← Total/Count
  • Totalling algorithm
    For a sushi conveyor, how could we find the total cost of all sushi on the conveyor?
    Total ← 0
    WHILE SushiDetected
    Total ← Total + Price
    ENDWHILE
  • Lowest algorithm
    For a sushi conveyor, how could we find the cheapest item on the conveyer?
    CheapestItem ← 0
    FirstItem ← TRUE
    WHILE SushiDetected
    IF FirstItem
    THEN
    CheapestItem ← FirstItem
    ELSE
    FirstItem ← FALSE
    IF PRICE < MIN
    MIN ← PRICE
    ENDIF
    ENDIF
    ENDWHILE
  • In a linear search, the items are examined in the sequence of the list.
  • Sorting
    Data sets often need to be sorted.
    Data sets can be sorted by:
    • Count Order
    • Alphabetical Order
    • Reverse alphabetical or count order
  • Bubble Sort
    1. Start with the left-most item
    2. Compare it to the one next to it
    3. If the one next to it is less, swap the items
    4. Repeat for all other items
    5. At the end of one pass through the list, the largest item is at the end of the list.
    Repeat the process until all the items are sorted
    Each pass results in the next last item being sorted