Algorithms

Spring 2013
course
navigation

Feb 7

Discuss homework answers .

continue data structures

Array : sequential memory locations; fixed size when created
# # Here's what one can look like in python. # data = [0]*100 # allocate 100 slots data[3] = 10 # put something in slot 3 x = data[52] # fetch something from slot 52
Linked List :
# # Last class we implemented a linked list with a python class, # using an instance for each node. We can also use python's dict, # using keywords for the internal data and link pieces. # # +--------+ +--------+ # | node0 | <----| node1 | # +--------+ +--------+ # node0 = {'data': 3, 'up': None} node1 = {'data': 10, 'up': node0}
Binary (Linked) Tree :
# root 40 # / \ # / \ # kid0 kid1 60 # kid0 = {'data': 20, left: None, right: None} kid1 = {'data': 60, left: None, right: None} root = {'data': 40, left: kid0, right: kid1} # balanced trees : nodes equally spread between left & right
Stack :
s = Stack() s.push(data0) s.push(data1) dat1 = s.pop() # last in, first out
Queue :
q = Queue() q.enqueue(data0) q.enqueue(data1) data0 = q.dequeue() # first in, first out
Dictionary :
d = Dictionary() d.insert(data, key) data = d.search(key) d.delete(key) # "priority queue" or "heap" (coming in chapter 4) data = d.max() # Might have this, if so "priority" thing data = d.min() # and/or this # list like data = d.after(key) # Or might have this (e.g. linked list) data = d.before(key) # and/or this (ditto).
Hash Table :
# e.g. python's dictionary structure index = hash(data) # try to get a unique array offset storage[index] = data # ... unless there is already data there example hash table & hash function (pg 89) storage[] = [0]*10000 H('cat') = 2*char('c') + 4*char('a') + 8*char('t') index('cat') = H('cat') mod 10000 storage[index('cat')] = 'cat'
Depending on time, continue to play around with coding some of these structures in python, using python dicts or classes.

javascript singly linked list

Here's the same idea in javascript
// A singly linked list in javascript, // using the same ideas we discussed in python. var a0 = { data: 0, up: null }; var a1 = { data: 1, up: a0 }; var a3 = { data: 3, up: a1 }; var print_list = function(node){ while (node != null){ // while not at end, console.log(" " + node.data); // print node = node.up; // follow the chain } }; print_list(a3)
http://cs.marlboro.edu/ courses/ spring2013/algorithms/ notes/ Feb_7
last modified Thursday February 7 2013 11:17 am EST