Chapter 19 Flashcards

"Computational thinking and Problem-Solving"

1
Q

linear search

A

loops and searches each element until the target is located

time: O(n), as time to search increases linearly in relation to the number of items in the list
space: O(1), constant amount of space

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

linear search python

A
def linearsearch(arr, target):
    for i in range(len(arr)):
        if arr[i] == target:
            print("Target found")
            return i
    print("Target not found")
    return -1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

binary search

A
  • find the middle item
  • check if value of middle item is equal to the target
  • if equal target is found
  • if not, compare if target is greater or lesser than mid, and discard the half of the list that doesn’t contain the target
  • repeat the above steps until the target is found
  • or low == high and target is still not found, then target is not in the list

time is o(log n) as the array is divided in half at each step
space is o(1) as it uses a constant amount of extra space

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

conditions necessary for a binary search

A

the list needs to be ordered

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

binary search python

A
low = 0
high = len(arr) - 1

while low <= high:
    mid = (low + high)//2
    if arr[mid] == target:
         print(f"target at index {mid}")
         break
    elif target > arr[mid]:
        low = mid + 1
    elif target < arr[mid]:
        high = mid - 1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

insertion sort

A

swaps/orders in one iteration by inserting data in correct place
uses less memory and time than bubble sort

time is o(n^2)
space is o(1) as it uses a constant amount of extra space

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

insertion sort python

A
for i in range(1, len(list)):
  cIndex = i
  while (cIndex > 0) and (list[cIndex - 1] > list[cIndex]):
     list[cIndex], list[cIndex - 1] = list[cIndex - 1], list[cIndex]
     cIndex -= 1
  • cIndex = current index
  • starts at one because list compares with previous, not post (post in bubble sort). 0th place will be swapped to correct position, 0-1 will cause error
  • checks all elements before the “element to be inserted” are in the correct position, then moves on
  • index increments, then the currentIndex (while not at the beginning of the list and while the elements before are unsorted (c-1 > c) checks all those before it if the swap has changed the order
  • while loop works backwards
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

bubble sort

A

Bubble sort compares adjacent elements in the list/array.
They are swapped if the elements are in the wrong order
The algorithm iterates through the array multiple times in passes, using a swap flag
On each pass, the largest unsorted element gets sorted to its correct position at the end of the array.
The process is repeated until the entire array is sorted.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

bubble sort python

A
for i in range(len(array) - 1): #-1 for zero indexing
    swapped = False
    for j in range(len(array)-i-1):  #compares all adjacent pairs. i stays the same during this inner loop, j increments
         if array[j] > array[j +1]:
            array[j], array[j+1] = array[j+1], array[j]
            swapped = True
    if swapped is False:
         break	 
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

ADTs and examples

A

Abstract Data Type
linked list
queue
stack
binary tree

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

linked list

A

a dynamic data structure of nodes and pointers, where items are not stored contiguously in memory.
the first node is the head, the last node is the tail

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

binary tree

A

an ADT with nodes arranged hierarchally starting with root at top, where each node has 2 descendants.
left pointer -> left subtree, right pointer -> right subtree
three modes of traversal:
- in order
- preorder
- post order

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

post order traversal

A
  • post order moves from the bottom of the tree up - left subtree, right subtree, then the root node. prints after seeing the node three times

python:

def postorder(self):
   if self.left is not None:
      self.left.postorder()
   if self.right is not None:
      self.right.postorder()
   print(self.data)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

pre order traversal

A
  • pre order visits the root node first, then the left subtree, then the right. prints after seeing the node for the first time.

python:

def preorder(self):
    print(self.data)  #prints first node it sees
    if self.left is not None:
      self.left.preorder()
    if self.right is not None:
      self.right.preorder()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

in order traversal

A

using 2D arrays

  • in order traversal prints the binary tree in order of ascending node data. prints after the program has seen the node twice.
  • procedure InOrder taking a parameter (current node being accessed)
  • Checking if left Node is empty (−1 or None)
  • ….if not empty, calls procedure recursively with left node as parameter
  • if it is empty, outputs the current node
  • checks if right Node is empty (−1 or None)
  • …if not empty, calls procedure recursively with right node as a parameter
  • Order is correct, left, root, right
def InOrder(ArrayNodes, RootNode):
    if ArrayNodes[RootNode][0] != -1:   #if left node is not empty
        InOrder(ArrayNodes, ArrayNodes[RootNode][0])  #recursively call to search left node
    print(str(ArrayNodes[RootNode][1]))     #print current node
    if ArrayNodes[RootNode][2] != -1:
        InOrder(ArrayNodes, ArrayNodes[RootNode][2])
def inorder(self): #in order traversal, with printing data
    if self.left is not None:
      self.left.inorder()   #keeps calling as long as there is a left node to search, 
    print(self.data)  #then prints. starts from smallest to largest
    if self.right is not None:  #unwinds, searches right subtree of "previous" node
      self.right.inorder()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

insertion binary tree

A
def insert(self, data):
    if self.data is None:
      self.data = data
    else:
      if data < self.data: #if the data is less than the current node's data
        if self.left is not None:  #if the left subtree exists/a left node exists
          self.left.insert(data)  #recursively call, checking left subtree
        else:
          self.left = Node(data)   #insert into current node's left if no left subtree exists

      elif data > self.data:
        if self.right is not None:
          self.right.insert(data)
        else:
          self.right = Node(data)

      else: #if data is equal to current node's data, do nothing (duplicate)
        return
				
17
Q

stack

A

a LIFO linear data structure. items are inserted and removed from the top/head

push, pop, peek, isEmpty, isFull, size etc

18
Q

justify using a linked list over an array to implement a stack (review this)

A

linked list is not restricted in size (dynamic data structure)
has greater freedom to expand to contract by adding or removing the nodes as necessary
allows more efficient editing using pointers

19
Q

queue

A

a FIFO data structure. deletions occur at the head, and insertions at the back

enqueue, dequeue, peek, size, isEmpty, isFull

20
Q

dictionary

A

made up of associated key-value pairs. values are accessed using a key

21
Q

graph

A

a graph is a collection of nodes or vertices between which there are edges.

22
Q

big O notation

A

mathematical notation used to describe the performance or complexity of an algorithm in relation to the time taken or the memory used for the task

23
Q

bubble sort big o (time and space)

A

TIME
best case: o(n)
on average: o(n^2)
worst case: o(n^2)

SPACE: o(1)

24
Q

insertion sort big o (time and space)

A

TIME
best case: o(n)
on average: o(n^2)
worst case: o(n^2)

SPACE: o(1)

25
Q

binary search big o (time and space)

A

TIME
best: o(1)
average: o(log n)
worst: o(log n)
o(log n) is less rapid than o(n)

SPACE: o(1)

26
Q

linear search big o (time and space)

A

TIME
best: o(1)
average: o(n)
worst: o(n)

SPACE: o(1)

27
Q

recursion

A

a process using a function or procedure that calls itself.
a recursive process must have a base case and a general case where the recursive call takes place.

28
Q

why is a stack used to implement recursion?

A

stack is a LIFO data structure
each recursive call is pushed onto the stack
…and is then popped as the function ends
enables unwinding/backtracking
which maintains the required order

29
Q

three essential features of recursion

A

a base case/stopping condition
a general case, which calls itself recursively and changes its state and moves towards the base case

unwinding can occur once the base case is reached