Download Randomized Quicksort - Algorithms and Data Structure - Outline | CS 561 and more Study notes Computer Science in PDF only on Docsity!
CS 561, Lecture 7
Jared Saia University of New Mexico
Today’s Outline
- Randomized Quicksort
- Sorting Lowerbound
- Bucket Sort
- Dictionary ADT
R-Partition
//PRE: A[p..r] is the array to be partitioned, p>=1 and r <= size // of A //POST: Let A’ be the array A after the function is run. Then // A’[p..r] contains the same elements as A[p..r]. Further, // all elements in A’[p..res-1] are <= A[i], A’[res] = A[i], // and all elements in A’[res+1..r] are > A[i], where i is // a random number between $p$ and $r$. R-Partition (A,p,r){ i = Random(p,r); exchange A[r] and A[i]; return Partition(A,p,r); }
Randomized Quicksort
//PRE: A is the array to be sorted, p>=1, and r is <= the size of A //POST: A[p..r] is in sorted order R-Quicksort (A,p,r){ if (p<r){ q = R-Partition (A,p,r); R-Quicksort (A,p,q-1); R-Quicksort (A,q+1,r); }
Analysis
- R-Quicksort is a randomized algorithm
- The run time is a random variable
- We’d like to analyze the expected run time of R-Quicksort
- To do this, we first need to learn some basic probability theory.
Plan of Attack
“If you get hold of the head of a snake, the rest of it is mere rope” - Akan Proverb
- We will analyze the total number of comparisons made by quicksort
- We will let X be the total number of comparisons made by R-Quicksort
- We will write X as the sum of a bunch of indicator random variables
- We will use linearity of expectation to compute the expected value of X
Notation
- Let A be the array to be sorted
- Let zi be the i-th smallest element in the array A
- Let Zi,j = {zi, zi+1,... , zj}
Indicator Random Variables
- Let Xi,j be 1 if zi is compared with zj and 0 otherwise
- Note that X = ∑n− 1 i=
∑n j=i+1 Xi,j
E(X) = E(
n∑− 1
i=
∑^ n j=i+
Xi,j) =
n∑− 1
i=
∑^ n j=i+
E(Xi,j)
Questions
2 k =^ O(log^ n)?
∑^ n k=
k
∑^ n k=
1 /k (10)
≤ 2(ln n + 1) (11)
- Where the last step follows by an integral bound on the sum (p. 1067)
Take Away
- The expected number of comparisons for r-quicksort is O(n log n)
- Competitive with mergesort and heapsort
- Randomized version is “better” than deterministic version
How Fast Can We Sort?
- Q: What is a lowerbound on the runtime of any sorting al- gorithm?
- We know that Ω(n) is a trivial lowerbound
- But all the algorithms we’ve seen so far are O(n log n) (or O(n^2 )), so is Ω(n log n) a lowerbound?
Comparison Sorts
- Definition: An sorting algorithm is a comparison sort if the sorted order they determine is based only on comparisons between input elements.
- Heapsort, mergesort, quicksort, bubblesort, and insertion sort are all comparison sorts
- We will show that any comparison sort must take Ω(n log n)
Comparisons
- Assume we have an input sequence A = (a 1 , a 2 ,... , an)
- In a comparison sort, we only perform tests of the form ai < aj, ai ≤ aj, ai = aj, ai ≥ aj, or ai > aj to determine the relative order of all elements in A
- We’ll assume that all elements are distinct, and so note that the only comparison we need to make is ai ≤ aj.
- This comparison gives us a yes or no answer
Decision Tree Model
- A decision tree is a full binary tree that gives the possible sequences of comparisons made for a particular input array, A
- Each internal node is labelled with the indices of the two elements to be compared
- Each leaf node gives a permutation of A
Decision Tree Model
- The execution of the sorting algorithm corresponds to a path from the root node to a leaf node in the tree.
- We take the left child of the node if the comparison is ≤ and we take the right child if the comparison is >
- The internal nodes along this path give the comparisons made by the alg, and the leaf node gives the output of the sorting algorithm.
Leaf Nodes
- Any correct sorting algorithm must be able to produce each possible permutation of the input
- Thus there must be at least n! leaf nodes
- The length of the longest path from the root node to a leaf in this tree gives the worst case run time of the algorithm (i.e. the height of the tree gives the worst case runtime)
Take Away
- We’ve just proven that any comparison-based sorting algo- rithm takes Ω(n log n) time
- This does not mean that all sorting algorithms take Ω(n log n) time
- In fact, there are non comparison-based sorting algorithms which, under certain circumstances, are asymptotically faster.
Bucket Sort
- Bucket sort assumes that the input is drawn from a uniform distribution over the range [0, 1)
- Basic idea is to divide the interval [0, 1) into n equal size regions, or buckets
- We expect that a small number of elements in A will fall into each bucket
- To get the output, we can sort the numbers in each bucket and just output the sorted buckets in order
Bucket Sort
//PRE: A is the array to be sorted, all elements in A[i] are between $0$ and $1$ inclusive. //POST: returns a list which is the elements of A in sorted order BucketSort(A){ B = new List[] n = length(A) for (i=1;i<=n;i++){ insert A[i] at end of list B[floor(n*A[i])]; } for (i=0;i<=n-1;i++){ sort list B[i] with insertion sort; } return the concatenated list B[0],B[1],...,B[n-1]; }
Bucket Sort
- Claim: If the input numbers are distributed uniformly over the range [0, 1), then Bucket sort takes expected time O(n)
- Let T (n) be the run time of bucket sort on a list of size n
- Let ni be the random variable givingthe number of elements in bucket B[i]
- Then T (n) = Θ(n) + ∑n− 1 i=0 O(n^2 i )
Analysis
- We know T (n) = Θ(n) + ∑n− 1 i=0 O(n 2 i )
- Taking expectation of both sides, we have
E(T (n)) = E(Θ(n) +
n∑− 1
i=
O(n^2 i ))
= Θ(n) +
n∑− 1
i=
E(O(n^2 i ))
= Θ(n) +
n∑− 1
i=
(O(E(n^2 i )))
- The second step follows by linearity of expectation
- The last step holds since for any constant a and random variable X, E(aX) = aE(X) (see Equation C.21 in the text)
Analysis
- We claim that E(n^2 i ) = 2 − 1 /n
- To prove this, we define indicator random variables: Xij = 1 if A[j] falls in bucket i and 0 otherwise (defined for all i, 0 ≤ i ≤ n − 1 and j, 1 ≤ j ≤ n)
- Thus, ni = ∑n j=1 Xij
- We can now compute E(n^2 i ) by expanding the square and regrouping terms
Analysis
E(ni 2 ) = E((
∑^ n j=
Xij)^2 )
= E(
∑^ n j=
∑^ n k=
XijXik)
= E(
∑^ n j=
X ij^2 +
∑ 1 ≤j≤n
∑ 1 ≤k≤n,k 6 =j
XijXik)
∑^ n j=
E(X ij^2 ) +
∑ 1 ≤j≤n
∑ 1 ≤k≤n,k 6 =j
E(XijXik))
Analysis
- We can evaluate the two summations separately. Xij is 1 with probability 1/n and 0 otherwise
- Thus E(X ij^2 ) = 1 ∗ (1/n) + 0 ∗ (1 − 1 /n) = 1/n
- Where k 6 = j, the random variables Xij and Xik are indepen- dent
- For any two independent random variables X and Y , E(XY ) = E(X)E(Y ) (see C.3 in the book for a proof of this)
- Thus we have that
E(XijXik) = E(Xij)E(Xik) = (1/n)(1/n) = (1/n^2 )
Implementing Dictionaries
- The simplest way to implement a dictionary ADT is with a linked list
- Let l be a linked list data structure, assume we have the following operations defined for l - head(l): returns a pointer to the head of the list - next(p): given a pointer p into the list, returns a pointer to the next element in the list if such exists, null otherwise - previous(p): given a pointer p into the list, returns a pointer to the previous element in the list if such exists, null otherwise - key(p): given a pointer into the list, returns the key value of that item - record(p): given a pointer into the list, returns the record value of that item
At-Home Exercise
Implement a dictionary with a linked list
- Q1: Write the operation Lookup(k) which returns a pointer to the item with key k if it is in the dictionary or null otherwise
- Q2: Write the operation Insert(k,r)
- Q3: Write the operation Delete(k)
- Q4: For a dictionary with n elements, what is the runtime of all of these operations for the linked list data structure?
- Q5: Describe how you would use this dictionary ADT to count the number of occurences of each word in an online book.
Dictionaries
- This linked list implementation of dictionaries is very slow
- Q: Can we do better?
- A: Yes, with hash tables, AVL trees, etc
Hash Tables
Hash Tables implement the Dictionary ADT, namely:
- Insert(x) - O(1) expected time, Θ(n) worst case
- Lookup(x) - O(1) expected time, Θ(n) worst case
- Delete(x) - O(1) expected time, Θ(n) worst case
Direct Addressing
- Suppose universe of keys is U = { 0 , 1 ,... , m − 1 }, where m is not too large
- Assume no two elements have the same key
- We use an array T [0..m − 1] to store the keys
- Slot k contains the elem with key k
Direct Address Functions
DA-Search(T,k){ return T[k];} DA-Insert(T,x){ T[key(x)] = x;} DA-Delete(T,x){ T[key(x)] = NIL;}
Each of these operations takes O(1) time
Direct Addressing Problem
- If universe U is large, storing the array T may be impractical
- Also much space can be wasted in T if number of objects stored is small
- Q: Can we do better?
- A: Yes we can trade time for space