advanced algorithmics (4ap) linear structures: li tlists ... · pdf fileadvanced algorithmics...

99
Advanced Algorithmics (4AP) Linear structures: Li t Q St k ti Lis ts, Queues, St acks, sorting,… Jaak Vilo Jaak Vilo 2009 Spring 1 MTAT.03.190 Text Algorithms Jaak Vilo

Upload: phungtu

Post on 13-Mar-2018

228 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Advanced Algorithmics (4AP)Linear structures: 

Li t Q St k tiLists, Queues, Stacks, sorting,…Jaak ViloJaak Vilo

2009 Spring

1MTAT.03.190 Text Algorithms Jaak Vilo

Page 2: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Lists: ArrayLists: Array

3 6 7 5 2

0 1 size MAX_SIZE-1

L = int[MAX_SIZE][ _ ]

L[2]=7

Page 3: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Lists: ArrayLists: Array

3 6 7 5 2

0 1 size MAX_SIZE-1

L = int[MAX_SIZE][ _ ]

L[2]=7

1 2 size MAX SIZE

3 6 7 5 2

1 2 size _

L[3]=7

Page 4: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Linear ListsLinear Lists

• Operations which one may want to perform on a linear list of n elements include:

– gain access to the kth element of the list to– gain access to the kth element of the list to examine and/or change the contents

i t l t b f ft th kth– insert a new element before or after the kthelement

– delete the kth element of the list

Reference: Knuth, The Art of Comptuer Programming, Vol 1,

Fundamental Algorithms, 3rd Ed., p.238‐9

Page 5: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Abstract Data Type (ADT)Abstract Data Type (ADT)

Hi h l l d fi iti f d t t• High‐level definition of data types

• An ADT specifiesAn ADT specifies– A collection of data– A set of operations on the data or subsets of the data

• ADT does not specify how the operations should be implementedp

• Examplesl k d bl ( )– vector, list, stack, queue, deque, priority queue, table (map), 

associative array, set, graph, digraph

Page 6: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

ADTADT

• A datatype is a set of values and an associated set of operations

A d t t i b t t iff it i l t l d ib d b it t• A datatype is abstract iff it is completely described by its set of operations regradless of  its implementation

• This means that it is possible to change the implementation• This means that it is possible to change the implementation of the datatype without changing its use

• The datatype is thus described by a set of proceduresThe datatype is thus described by a set of procedures

• These operations are the only thing that a user of the abstraction can assumeabstraction can assume

Page 7: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Abstract data types:Abstract data types:

• DictionaryDictionary

• Stack (LIFO)

• Queue (FIFO)

• Queue (double‐ended)Queue (double ended)

Page 8: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

DictionaryDictionary

• Container of key‐element pairs

• Required operations:– insert( k,e ),

– remove( k ),( )

– find( k ),

– isEmpty()p y()

• May also support (when an order is provided):– closestKeyBefore( k )closestKeyBefore( k ),

– closestElemAfter( k )

• Note: No duplicate keys• Note: No duplicate keys

Page 9: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Some data structures for Dictionary ADTSome data structures for Dictionary ADT• Unordered 

– Array

– Sequence

• Ordered – Array

Sequence (Skip Lists)– Sequence (Skip Lists)

– Binary Search Tree (BST)

– AVL

– (2; 4) Trees

– B‐Trees

• Valued– Hash Tables

– Extendible Hashing

Page 10: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Lists: ArrayLists: Array

3 6 7 5 2

0 1 size MAX_SIZE-1

size

3 6 7 8 2

0 1 size

5 2 Insert 8 after L[2]

3 6 7 8 2

0 1 size

5 2 Delete last3 6 7 8 25 2 Delete last

Page 11: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Lists: ArrayLists: Array• Insert O(n)• Insert O(n) • Delete O(n)• Access i O(1)• Insert to end O(1)

size

Insert to end O(1)• Delete from end O(1)• Search O(n)

3 6 7 8 2

0 1 size

5 2 Insert 8 after L[2]

3 6 7 8 2

0 1 size

5 2 Delete last3 6 7 8 25 2 Delete last

Page 12: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

StackStack

• push(x) ‐‐ add to end (add to top)push(x) add to end (add to top)

• pop() ‐‐ fetch from end (top)

• O(1) in all reasonable casesO(1) in all reasonable cases 

• LIFO – Last In, First Out

Page 13: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Linear ListsLinear Lists

• Other operations on a linear list may include:– determine the number of elements

– search the list

sort a list– sort a list

– combine two or more linear lists

– split a linear list into two or more lists

– make a copy of a listpy

Page 14: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Linked listsLinked listshead tail

Singly linked

head tail

Doubly linked

Page 15: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Linked lists: add/deleteLinked lists: add/deletehead tail

head tail

size

Page 16: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

OperationsOperations

• Array indexed from 0 to n – 1:k = 1 1 < k < n k = n

access/change the kth element O(1) O(1) O(1)

insert before or after the kth element O(n) O(n) O(1)

delete the kth element O(n) O(n) O(1)

• Singly‐linked list with head and tail pointers

delete the kth element O(n) O(n) O(1)

k = 1 1 < k < n k = naccess/change the kth element O(1) O(n) O(1)

insert before or after the kth element O(1) O(n) O(1)1 O(n) O(1)

1 under the assumption we have a pointer to the kth node, O(n) otherwise

insert before or after the kth element O(1) O(n) O(1)1 O(n) O(1)

delete the kth element O(1) O(n) O(n)

Page 17: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Improving Run Time EfficiencyImproving Run‐Time Efficiency

• We can improve the run‐time efficiency of a linked list by using a doubly‐linked list:y g y

Singly‐linked list:

Doubly‐linked list:

– Improvements at operations requiring access to the previous nodethe previous node

– Increases memory requirements...

Page 18: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Improving EfficiencyImproving Efficiency

• Comparing the tables:Singly‐linked list:

k = 1 1 < k < n k = naccess/change the kth element O(1) O(n) O(1)

insert before or after the kth element O(1) O(n) O(1)1 O(n) O(1)

Doubly‐linked list:

insert before or after the kth element O(1) O(n) O(1)1 O(n) O(1)

delete the kth element O(1) O(n) O(n)

yk = 1 1 < k < n k = n

access/change the kth element O(1) O(n) O(1)1

1 under the assumption we have a pointer to the kth node O(n) otherwise

insert before or after the kth element O(1) O(1)1 O(1)

delete the kth element O(1) O(1)1 O(1)

under the assumption we have a pointer to the kth node, O(n) otherwise

Page 19: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Introduction to linked listsIntroduction to linked lists: : definitiondefinitionConsider the following struct definition

struct node{{

string word;int num;

//node *next; // pointer for the next node};

node *p = new node;

? ?

num word next

p ?

Page 20: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Introduction to linked listsIntroduction to linked lists: : inserting a nodeinserting a nodeggnode *p;

dp = new node;p->num = 5; p->word = "Ali";p ;p->next = NULL

5 Ali

num word next

p

?

Page 21: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Introduction to linked listsIntroduction to linked lists: : adding a new nodeadding a new nodegg

How can you add another node that is pointed by p->link?How can you add another node that is pointed by p >link?

node *p;p = new node;p = new node;p->num = 5; p->word = "Ali";> t NULLp->next = NULL;

node *q;

q

5 Ali

num word link

?p

?

Page 22: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Introduction to linked listsIntroduction to linked listsnode *p;p = new node;p = new node;p->num = 5; p->word = "Ali";p->next = NULL;

node *q;node q;q = new node;

q

5 Ali

num word link

? ? ?

num word link

?p

num link?

Page 23: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Introduction to linked listsIntroduction to linked listsnode *p, *q;p = new node;p = new node;p->num = 5; p->word = "Ali";p->next = NULL;

q = new node;q new node;q->num=8;q->word = "Veli";

q

5 Ali

num word next

? 8 Veli

num word next

?p

num next?

Page 24: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Introduction to linked listsIntroduction to linked listsnode *p, *q;p = new node;p = new node;p->num = 5; p->word = "Ali";p->next = NULL;

q = new node;q new node;q->num=8;q->word = "Veli";p->next = q;q->next = NULL;

q

5 Ali

num word link

? 8 Veli

num word link

p

num link

Page 25: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

PointersPointers

d d l t• p = new node ;  delete p ; 

• p = new node[20] ; p [ ] ;

( f( ) ) f• p = malloc( sizeof( node ) ) ;   free p ; 

• p = malloc( sizeof( node ) * 20 ) ; 

• (p+10)‐>next = NULL ;  /* 11th elements */

Page 26: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Book keepingBook‐keeping

• malloc, new – “remember” what has beencreated free(p), delete (C/C++)(p) ( )

• When you need many small areas to beallocated reserve a big chunk (array) andallocated, reserve a big chunk (array) and maintain your own set of free objects

• Elements of array of objects can be pointed bythe pointer to an object.the pointer to an object.

Page 27: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

ObjectObject

• Object = new object_type ; 

• Equals to creating a new object with necessaryi f ll d (d l f i )size of allocated memory (delete can free it)

Page 28: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Some linksSome links

• http://en.wikipedia.org/wiki/Pointer

• Pointer basics: h // lib f d d /106/http://cslibrary.stanford.edu/106/

• C++ Memory Management : What is the difference between malloc/free and new/delete?between malloc/free and new/delete?

– http://www.codeguru.com/forum/showthread.php?t 401848p?t=401848

Page 29: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

I want to test and understandI want to test and understand…

• If you want to test pointers and linked list etc.If you want to test pointers and linked list etc. data structures, but do not have pointersfamiliar (yet)familiar (yet)

• Use arrays and indexes to array elementsinsteadinstead…

Page 30: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Replacing pointers with array indexReplacing pointers with array indexhead=3 head

/

7

5

8

1

4

1 2 3 4 5 6 7next

key8 4 7

7

5

8

/

4

3

yprev

Page 31: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Maintaining list of free objectsMaintaining list of free objectshead=3 head

/

7

5

8

1

4

1 2 3 4 5 6 7next

key8 4 7

7

5

8

/

4

3

yprev

head=3 free=6 free = -1 => array is full

/

7

4 5

8

/ 1

4

7 21 2 3 4 5 6 7

next

key

allocate object:new = free;free = next[free] ;7

5

8

/

4

3

keyprev

free next[free] ;free object x

next[x]= freefree = xee

Page 32: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Multiple lists single free listMultiple lists, single free list

h d1 3 8 4 7head1=3 => 8, 4, 7head2=6 => 3, 9free =2 (2)

/

7

4 5

8

/ 1

4

7

3

/

9

1 2 3 4 5 6 7next

key 7

5

8

/

4

3

3

/

9

6

keyprev

Page 33: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Hack: allocate more arraysHack: allocate more arrays …

AA 1 2 3 4 5 6 7

8 9 10 11 12 13 14

AAuse integer division and mod

8 9 10 11 12 13 14

15 16 17 18 19 20 21

AA[ (i-1)/7 ] -> [ (i -1) % 7 ]

LIST(10) = AA[ 1 ][ 2 ]

Page 34: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,
Page 35: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Queue(basic idea, does not contain all controls!)

3 6 7 5 2

F L MAX_SIZE-1

F L MAX_SIZE-1

7 5 2

_

First = List[F] Pop_first : { return List[F++] }

Last = List[L-1] Pop_last : { return List[--L] }

Full: return ( L==MAX_SIZE )Empty: F< 0 or F >= L

Page 36: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Circular bufferCircular buffer

• A circular buffer or ring buffer is a data gstructure that uses a single fixed‐sizea single, fixed size buffer as if it were connected end toconnected end‐to‐end. This structure lends itself easily to buffering data streams.

Page 37: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Circular QueueCircular Queue

3 6

FL

7 5 2

MAX_SIZE-1

First List[F]First = List[F]

Add_to_end( x ) : { List[L]=x ; L= (L+1) % MAX_SIZE ] } // % = modulo

Last = List[ (L-1+MAX_SIZE) % MAX_SIZE ]

Full: return ( (L+1)%MAX SIZE == F )Full: return ( (L+1)%MAX_SIZE == F )Empty: F==L

FL, MAX_SIZE-1

3 6 7 5 2

Page 38: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

QueueQueue

• enqueue(x) ‐ add to end

• dequeue() ‐ fetch from beginningdequeue() fetch from beginning

• FIFO – First In First Out

• O(1) in all reasonable cases

Page 39: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

StackStack

• push(x) ‐‐ add to end (add to top)push(x) add to end (add to top)

• pop() ‐‐ fetch from end (top)

• O(1) in all reasonable casesO(1) in all reasonable cases

• LIFO – Last In, First Out

Page 40: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Stack based languagesStack based languages

• Implement a postfix calculator– Reverse Polish notation

5 4 3 * 2 + > 5+((4*3) 2)• 5 4 3 * 2 ‐ + => 5+((4*3)‐2)

• Very simple to parse and interpret

• FORTH, Postscipt are stack‐based languages, p g g

Page 41: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Array based stackArray based stack

• How to know how big a stack shall be? 

3 6 7 53 6 7 5

3 6 7 5 2

• When full dynamically allocate bigger tableWhen full, dynamically allocate bigger table, and copy all previous values there

• O(n) ?O(n) ? 

Page 42: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

• When full, create 2x bigger table, copy previous n elements:p

Af 2k i i f O( )• After every 2k insertions, perform O(n) copy

• O(n) indivudual insertions + 

• n/2 + n/4 + n/8 …  copy‐ing 

• Total: O(n) effort!Total: O(n) effort!

Page 43: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

• when n=32 ‐> 33   (copy 32, insert 1)

• delete: 33‐>32delete: 33 >32– should you delete immediately?

D l l h b l h 1/4 h f ll– Delete only when becomes less than 1/4th full

– Have to delete at least n/2 to decrease

– Have to add at least n to increase sizeHave to add at least n to increase size

– Most operations, O(1) effort  

B f i k O( )– But few operations take O(n) to copy

– For any m operations, O(m) time

Page 44: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Lists and dictionaryLists and dictionary…

• How to maintain a dictionary using (linked) lists?

• Is k in D ? th h ll l t d f D t t if d k O( )– go through all elements d of D, test if d==k O(n)

– If sorted: d= first(D); while( d<=k ) d=next(D); 

– on average <= n/2 tests …

• Add(k D) => insert(k D) = O(1) or O(n) – testAdd(k,D) => insert(k,D) = O(1)   or O(n)  test for uniqueness

Page 45: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Array based sorted listArray based sorted list

• is d in D ?is d in D ? 

• Binary search in D

Page 46: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Binary search / recursiveBinary search / recursiveBinarySearch(A[0..N‐1], value, low, high) 

if (high < low) 

return ‐1 // not found 

mid = low + ((high ‐ low) / 2)  // Note: not (low + high) / 2 !!

if (A[mid] > value) 

return BinarySearch(A, value, low, mid‐1) 

else if (A[mid] < value) 

return BinarySearch(A, value, mid+1, high) 

elsereturnmid // found 

}

Page 47: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Binary search IterativeBinary search – Iterative

h( [ ] l )BinarySearch(A[0..N‐1], value) 

low = 0 ; high = N ‐ 1 ;low = 0 ;  high = N  1 ;

while (low <= high) { 

mid = low + ((high ‐ low) / 2) // Note: not (low + high) / 2 !!

if (A[mid] > value) 

high = mid ‐ 1 

l if (A[ id] l )else if (A[mid] < value) 

low = mid + 1 

elseelsereturnmid // found 

} return 1 // not foundreturn ‐1 // not found 

}

Page 48: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Work performedWork performed

• x <=> A[18] ?    <

• x <=> A[9] ? >x < > A[9] ? >

• x <=> A[13] ?    ==

1 3618

• O(lg n)

Page 49: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

SortingSorting

• given a list, arrange values so thatL[1] <= L[2] <= … <= L[n][ ] [ ] [ ]

• n elements =>  n!  possible orderings

• One test L[i] <= L[j] can divide n! to 2 – Make a binary tree and calculate the depthy p

• log( n! ) = O( n log n ) 

H l b d f i i O( l )• Hence, lower bound for sorting is O( n log n )– using comparisons…

– (proved in previous lecture on blackboard)

Page 50: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

The divide‐and‐conquer design paradigm

1. Divide the problem (instance) into1. Divide the problem (instance) into subproblems.

2 C h b bl b l i h2. Conquer the subproblems by solving them recursively.

3. Combine subproblem solutions.

Page 51: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Merge sortMerge sort

Merge‐Sort(A,p,r)

if p<rif p<r

then q = (p+r)/2 // floor

Merge‐Sort( A, p, q ) 

Merge‐Sort( A q+1 r)Merge Sort( A, q+1,r)

Merge( A, p, q, r )

It was invented by John von Neumann in 1945.

Page 52: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

ExampleExample

• Applying the merge sort algorithm:

Page 53: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Merge of two lists: Θ(n)Merge of two lists: Θ(n)

A, B – lists to be merged

L = new list; // emptyL   new list;   // empty

while( A not empty and B not empty ) if A.first() <= B.first()

then append( L, A.first() ) ; A = rest(A) ; pp ( () ) ( )

else append( L, B.first() ) ; B = rest(B) ;

append( L A); // all remaining elements of Aappend( L, A); // all remaining elements of A

append( L, B );  // all remaining elements of B

return L

Page 54: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Wikipedia / viz.ue

Val

Pos in array

Page 55: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Run time Analysis of Merge SortRun‐time Analysis of Merge Sort

• Thus, the time required to sort an array of size n > 1 is:– the time required to sort the first half,

the time required to sort the second half and– the time required to sort the second half, and

– the time required to merge the two lists

• That is:

1)1( nΘ

1)(T21)1(

)T(2 nn

nn n Θ

Θ

Page 56: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,
Page 57: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Merge sortMerge sort

• Worst case, average case, best case …

Θ( n log n )Θ( n log n )

• Common wisdom:– Requires additional space for merging (in case of arrays)

• Homework: develop in‐place merge of two listsHomework: develop in place merge of two listsimplemented in arrays /compare speed/

a b

L[a] <= L[b]L[a] > L[b]

a b a b

Page 58: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

QuicksortQuicksort

• Proposed by C.A.R. Hoare in 1962.Proposed by C.A.R. Hoare in 1962.

• Divide‐and‐conquer algorithm.

• Sorts “in place”(like insertion sort, but not like merge sort).g )

• Very practical (with tuning).

Page 59: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,
Page 60: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

QuicksortQuicksort

Page 61: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,
Page 62: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Partitioning version 2gL R

L R

<= pivot

> pivoti j

pivot = A[R]; //

L R > pivoti j

pivot = A[R];     // 

i=L; j=R‐1;

while( i<j )

while ( A[i] <= pivot ) i++ ; ( [ ] p ) ;

while ( A[j] >   pivot ) j‐‐ ; 

if ( i < j ) { tmp= A[i]; A[i]=A[j]; A[j]=A[i] }if ( i < j )  { tmp= A[i]; A[i]=A[j]; A[j]=A[i] }

A[R]=A[i];  L Rij

A[R]=pivot;

return i;L Rij

Page 63: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

QuicksortQuicksort

• See http://www.ece.uwaterloo.ca/~ece250/Lectures/Slides/7.06.QuickSort.pptfor detailed examplep

Page 64: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Wikipedia / “video”Wikipedia /  video

Page 65: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,
Page 66: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,
Page 67: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,
Page 68: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,
Page 69: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,
Page 70: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-046JFall-2005/VideoLectures/detail/embed04.htm

Page 71: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,
Page 72: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,
Page 73: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,
Page 74: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,
Page 75: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,
Page 76: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,
Page 77: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,
Page 78: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,
Page 79: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,
Page 80: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,
Page 81: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

OkOk…

• lists – a versatile data structure for variouslists a versatile data structure for variouspurposes

• Sorting – a typical algorithm (many ways)g yp g ( y y )

• But most of the important (e.g. update) tasksseem to be O(n), which is bad

Page 82: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Can we search fasterin linked lists?

• Linked lists:Linked lists:– what is the “mid‐point” of any sublist ?

Th f bi h b d– Therefore, binary search can not be used…

• Or can it ? 

Page 83: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,
Page 84: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Skip listsSkip lists

• Build several lists at different “skip” steps

• O(n) list

• Level 1:  ~ n/2 

• Level 2: ~ n/4Level 2:    n/4 

• …

• Level log n  ~ 2‐3 elements…

Page 85: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Skip ListSkip List

typedef struct nodeStructure *node;

typedef struct nodeStructure{typedef struct nodeStructure{

keyType key;

valueType value;

node forward[1]; /* variable sized array of forward pointers */node forward[1]; /  variable sized array of forward pointers  /

};

Page 86: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Skip ListsSkip Lists

S2

S3

15

S0

S1

10 362315

2315

0

2/17/2009 12:33 AM Skip Lists 86

Page 87: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Outline and ReadingWhat is a skip list (§3.5)OperationsOperations Search (§3.5.1)

Insertion (§3 5 2) Insertion (§3.5.2) Deletion (§3.5.2)

I l t tiImplementationAnalysis (§3.5.3) Space usage Search and update times

2/17/2009 12:33 AM Skip Lists 87

Page 88: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

What is a Skip ListA skip list for a set S of distinct (key, element) items is a series of lists S0, S1 , … , Sh such that Each list Si contains the special keys and i List S0 contains the keys of S in nondecreasing order Each list is a subsequence of the previous one, i.e.,

S0 S1 … Sh List Sh contains only the two special keys

We show how to use a skip list to implement the dictionary ADT

31S2

S3

56 64 78 31 34 44 12 23 26

64 31 34 23

S0

S1

2/17/2009 12:33 AM Skip Lists 88

56 64 78 31 34 44 12 23 26S0

Page 89: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

SearchW h f k i ki li t f llWe search for a key x in a a skip list as follows: We start at the first position of the top list At the current position p, we compare x with y key(after(p))

x y: we return element(after(p))x y: we “scan forward” x y: we “drop down”y p

If we try to drop down past the bottom list, we return NO_SUCH_KEYExample: search for 78

S2

S3

31

S

S1

2

64 31 34 23

56 64 7831 34 4412 23 26

2/17/2009 12:33 AM Skip Lists 89

S0 56 64 78 31 34 44 12 23 26

Page 90: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Randomized AlgorithmsA d i d l ith W l th t dA randomized algorithmperforms coin tosses (i.e., uses random bits) to control its execution

We analyze the expected running time of a randomized algorithm under the following assumptionsits execution

It contains statements of the type

the following assumptions the coins are unbiased, and the coin tosses are

independentb random()if b 0

do A …

independentThe worst-case running time of a randomized algorithm is often la ge b t has e loelse { b 1}

do B … Its running time depends on

often large but has very low probability (e.g., it occurs when all the coin tosses give “heads”)Its running time depends on

the outcomes of the coin tosses

heads )We use a randomized algorithm to insert items into a skip list

2/17/2009 12:33 AM Skip Lists 90

a skip list

Page 91: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

T i t it ( ) i t ki li t d i d

InsertionTo insert an item (x, o) into a skip list, we use a randomized algorithm: We repeatedly toss a coin until we get tails, and we denote with i

the number of times the coin came up headsthe number of times the coin came up heads If i h, we add to the skip list new lists Sh1, … , Si 1, each

containing only the two special keysWe search for in the skip list and find the positions We search for x in the skip list and find the positions p0, p1 , …, pi of the items with largest key less than x in each list S0, S1, … , Si

For j 0, …, i, we insert item (x, o) into list Sj after position pj

Example: insert key 15 with i 2Example: insert key 15, with i 2

S2

S2

S3

15p2

10 36

23

23

S

S1

2

S

S1

2

10 362315

2315p0

p1

2/17/2009 12:33 AM Skip Lists 91

10 3623S0 S0 10 362315

Page 92: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

DeletionTo remove an item with key x from a skip list, we proceed as follows: We search for x in the skip list and find the positions p0 p1 pi We search for x in the skip list and find the positions p0, p1 , …, pi

of the items with key x, where position pj is in list Sj

We remove positions p0, p1 , …, pi from the lists S0, S1, … , Si

We remove all but one list containing only the two special keys We remove all but one list containing only the two special keysExample: remove key 34

S2

S2

S3

34p2

4512 23

23

S

S1

2

S

S1

2

4512 23 34

23 34p0

p1

2/17/2009 12:33 AM Skip Lists 92

4512 23S0S0 4512 23 34

Page 93: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

ImplementationWe can implement a skip list with quad-nodesA quad-node stores:A quad-node stores: item link to the node before quad-node link to the node after link to the node below link to the node after

x link to the node after

Also, we define special keys PLUS_INF and MINUS_INF, and we modify the keyand we modify the key comparator to handle them

2/17/2009 12:33 AM Skip Lists 93

Page 94: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Space UsageC id ki li i hThe space used by a skip list

depends on the random bits used by each invocation of the

Consider a skip list with nitems By Fact 1, we insert an item used by each invocation of the

insertion algorithmWe use the following two basic

y ,in list Si with probability 12i

By Fact 2, the expected size of list Si is n2i

probabilistic facts:Fact 1: The probability of getting i

consecutive heads when

i

The expected number of nodes used by the skip list is

flipping a coin is 12i

Fact 2: If each of n items is present in a set with

nnn h

ii

h

ii 2

21

2 00

pprobability p, the expected size of the set is np

Thus, the expected space usage of a skip list with nitems is O(n)

2/17/2009 12:33 AM Skip Lists 94

items is O(n)

Page 95: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

HeightThe running time of the search an insertion algorithms is affected by the

Consider a skip list with nitems By Fact 1, we insert an item in algorithms is affected by the

height h of the skip listWe show that with high probability a skip list with

list Si with probability 12i

By Fact 3, the probability that list Si has at least one item is t t 2iprobability, a skip list with n

items has height O(log n)We use the following

at most n2i

By picking i 3log n, we have that the probability that S3log nh t l t it iadditional probabilistic fact:

Fact 3: If each of n events has probability p, the probability

has at least one item isat most

n23log n nn3 1n2

Th ki li i h ip y p, p ythat at least one event occurs is at most np

Thus a skip list with n items has height at most 3log n with probability at least 1 1n2

2/17/2009 12:33 AM Skip Lists 95

Page 96: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Search and Update TimesTh h ti i ki li t Wh f d iThe search time in a skip list is proportional to the number of drop-down

steps plus

When we scan forward in a list, the destination key does not belong to a higher list

A f d t isteps, plus the number of scan-forward

stepsTh d d t

A scan-forward step is associated with a former coin toss that gave tails

By Fact 4 in each list theThe drop-down steps are bounded by the height of the skip list and thus are O(log n) with high probability

By Fact 4, in each list the expected number of scan-forward steps is 2Th th t d b fwith high probability

To analyze the scan-forward steps, we use yet another p obabilistic fact

Thus, the expected number of scan-forward steps is O(log n)We conclude that a search in a ki li t t k O(l )probabilistic fact:

Fact 4: The expected number of coin tosses required in order to get tails is 2

skip list takes O(log n) expected timeThe analysis of insertion and

2/17/2009 12:33 AM Skip Lists 96

to get tails is 2 deletion gives similar results

Page 97: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

Summary

A skip list is a data structure for

Using a more complex probabilistic analysis

dictionaries that uses a randomized insertion algorithm

probabilistic analysis, one can show that these performance algorithm

In a skip list with nitems

bounds also hold with high probability

The expected space used is O(n)

The expected search

Skip lists are fast and simple to implement in practice The expected search,

insertion and deletion time is O(log n)

practice

2/17/2009 12:33 AM Skip Lists 97

Page 98: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,
Page 99: Advanced Algorithmics (4AP) Linear structures: Li tLists ... · PDF fileAdvanced Algorithmics (4AP) Linear structures: Li tLists, Queues, St kStacks ... – vector, list, stack, queue,

ConclusionsConclusions

• Abstract data types hide implementations

• Important is the functionality of the ADTImportant is the functionality of the ADT

• Data structures and algorithms determine thed f h i dspeed of the operations on data

• Linear data structures provide good versatilityp g y

• Sorting – a most typical need/algorithm

• Sorting in O(n log n)   Merge Sort, Quicksort

• Solving Recurrences – means to analyseSolving Recurrences means to analyse

• Skip lists – log n randomised data structure