Docsity

UNIT 6A Organizing Data: Lists Last Two Weeks, Study notes of Data Structures and Algorithms

Partial preview of the text

Download UNIT 6A Organizing Data: Lists Last Two Weeks and more Study notes Data Structures and Algorithms in PDF only on Docsity!

UNIT 6A

Organizing Data: Lists

Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 1

Last Two Weeks

  • Algorithms: Searching and sorting
  • Problem solving technique: Recursion
  • Asymptotic worst‐case analysis using the big O

notation

Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 2

This Week

  • Observe: The choice of how to organize your data

determines how efficiently you can do certain

types of computation

  • Data structures
    • Arrays, linked lists, stacks, queues, hash tables, trees, graphs …
  • Representation of dynamic sets and supporting

operations such as search, insert, delete …

3

Data Structure

  • The organization of data is a very important issue for computation.
  • A data structure is a way of storing data in a computer so that it can be used efficiently. - Choosing the right data structure will allow us to develop certain algorithms for that data that are more efficient. - An array (or list) is a very simple data structure for holding a sequence of data.

Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 4

Linked Lists

  • Another data structure that stores a sequence of data values is the linked list.
  • Data values in a linked list do not have to be stored in adjacent memory cells.
  • To accommodate this feature, each data value has an additional “pointer” that indicates where the next data value is in computer memory.
  • In order to use the linked list, we only need to know where the first data value is stored.

Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 7

Linked List Example

  • Linked list to store the sequence: 50, 42, 85, 71, 99

Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 8

address data next 100 42 148 108 99 0 (null) 116 124 50 100 132 71 108 140 148 85 132 156

Starting Location of List (head) 124

Assume eachinteger and pointer requires 4 bytes.

Linked List Example

  • To insert a new element, we only need to change a few pointers.
  • Example: Insert 20 after 42.

Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 9

address data next 100 42 156 108 99 0 (null) 116 124 50 100 132 71 108 140 148 85 132 156 20 148

Starting Location of List (head) 124

Drawing Linked Lists Abstractly

• L = [50, 42, 85, 71, 99]

  • Inserting 20 after 42:

Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 10

50 42 85 71 99 null

head

50 42 85 71 99 null

head

20 step 2 step 1

We link the new node to the list before breaking the existing link.

2D Arrays in Ruby

data = [ [ 1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ]

data[0] => [1, 2, 3, 4] data[1][2] => 7 data[2][5] => nil data[4][2] => undefined method '[]' for nil

Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 13

0 1 2 3 0 1 2 3 4 1 5 6 7 8 2 9 10 11 12

2D Array Example in Ruby

  • Find the sum of all elements in a 2D array def sumMatrix(table) sum = 0 for row in 0..table.length-1 do for col in 0..table[row].length-1 do sum = sum + table[row][col] end end return sum end

Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 14

number of rows in the table

number of columns in the given row of the table

Tracing the Nested Loop

row col sum 0 0 1 0 1 3 0 2 6 0 3 10 1 0 15 1 1 21 1 2 28 1 3 36 2 0 45 2 1 55 2 2 66 2 3 78

Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 15

0 1 2 3 0 1 2 3 4 1 5 6 7 8 2 9 10 11 12

for row in 0..table.length-1 do for col in 0..table[row].length-1 do sum = sum + table[row][col] end end

table.length = 3 table[row].length = 4 for every row

Stacks

  • A stack is a data structure that works on the principle of Last In First Out (LIFO). - LIFO: The last item put on the stack is the first item that can be taken off.
  • Common stack operations:
    • Push – put a new element on to the top of the stack
    • Pop – remove the top element from the top of the stack
  • Applications: calculators, compilers, programming

Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 16

Evaluating RPN with a Stack

Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 19

A

S

i == A.length?

Pop top 2 numbers Perform operation Push x on S Push result on S

i  0

Output Pop S

yes no

A

x  A[i]

Is x a number? yes

no

i  i + 1 23 – 3 = 20

23 3 - 4 6 + /

23

23 3 - 4 6 + /

3 23

23 3 - 4 6 + /

20

23 3 - 4 6 + /

4 20

23 3 - 4 6 + /

6 4 20

23 3 - 4 6 + /

20

4 + 6 = 10 10 20

23 3 - 4 6 + /

20 / 10 = 2

2

23 3 - 4 6 + /

Answer: 2

Example Step by Step

  • RPN: 23 3 - 4 6 + /
  • Stack Trace:

Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 20

Stacks in Ruby

  • You can treat arrays (lists) as stacks in Ruby. stack x stack = [] [] stack.push(1) [1] stack.push(2) [1,2] stack.push(3) [1,2,3] x = stack.pop() [1,2] 3 x = stack.pop() [1] 2 x = stack.pop() [] 1 x = stack.pop() nil nil

Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 21

Queues

  • A queue is a data structure that works on the principle of First In First Out (FIFO). - FIFO: The first item stored in the queue is the first item that can be taken out.
  • Common queue operations:
    • Enqueue – put a new element in to the rear of the queue
    • Dequeue – remove the first element from the front of the queue
  • Applications: printers, simulations, networks

Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 22

Another way

  • Set up a large number of “buckets”.
  • Place each exam into a bucket based on some function. - Example: 100 buckets, each labeled with a value from 00 to 99. Use the student’s last two digits of their student ID number to choose the bucket.
  • Ideally, if the exams get distributed evenly, there will be only a few exams per bucket. - Assistant: O(n) putting n exams into the buckets - Professor: O(1) search for an exam by going directly to the relevant bucket and searching through a few exams. Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 25

Hashing

26

key key

key

Universe of keys Hash Table

h(key2)

A hash function h is used to map keys to hash-table slots

h(key3)

h(key1)

Strings and ASCII codes

s = "hello" for i in 0..s.length-1 do print s[i], "\n" end

104 101 108 108 111

Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 27

You can treat a string like an array in Ruby. If you access the ith character, you get the ASCII code for that character.

Hash table

  • Let’s assume that we are going to store only lower case strings into an array ( hash table ).

table1 = Array.new(26) => [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]

Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 28

Hash function (cont’d)

  • Using the hash function h:
    • “aardvark” would be stored in an array at index 0
    • “beaver” would be stored in an array at index 1
    • “kangaroo” would be stored in an array at index 10
    • “whale” would be stored in an array at index 22

table => ["aardvark", "beaver", nil, nil, nil, nil, nil, nil, nil, nil, "kangaroo", nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, "whale", nil, nil, nil] Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 31

Hash function (cont’d)

  • But if we try to insert “bunny” and “bear” into the hash table, each word overwrites the previous word since they all hash to index 1:

>> insert(table1,"bunny") >> insert(table1,"bear") >> table => ["aardvark", "bear", nil, nil, nil, nil, nil, nil, nil, nil, "kangaroo", nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, "whale", nil, nil, nil] Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 32

Revised Hash table

  • Let’s make our hash table an array of arrays (an array of “buckets”)
  • Each bucket can hold more than one string. table2 = Array.new(26) for i in 0..25 do table2[i] = [] end => [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]

Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 33

Revised insert function

**def insert(table, key)

find the bucket (array) in the table

array using the hash function h

bucket = table[h(key)]

append the key string to the bucket

array

bucket << key end**

Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 34

First Try

def h(string) k = 0 for i in 0..string.length-1 do k = string[i] + k end return k end h(“hello”) => 532 h(“olleh”) => 532 Permutations still give same index (collision) and numbers are high.

Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 37

Second Try

def h(string) k = 0 for i in 0..string.length-1 do k = string[i] + k end return k end h(“hello”) => 448378203247 h(“olleh”) => 478560413032* Better, but numbers are still high. We probably don’t want to (or can’t) create arrays that have indices this large. Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 38

Third Try

def h(string, tablesize) k = 0 for i in 0..string.length-1 do k = string[i] + k end return k % tablesize end*

We can use the modulo operator to take the large values and map them to indices for a smaller array.

Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 39

Revised insert function

**def insert(table, key)

find the bucket (array) in the table

array using the hash function h

bucket = table[h(key, table.length)]

append the key string to the bucket

array

bucket << key end**

Carnegie Mellon University - CORTINA^ 15110 Principles of Computing, 40