430 likes | 594 Vues
Sorting. How fast can we sort?. All the sorting algorithms we have seen so far are comparison sorts: only use comparisons to determine the relative order of elements. The best worst-case running time that we’ve seen for comparison sorting is O( nlgn ). Is O( nlgn )the best we can do?
E N D
How fast can we sort? • All the sorting algorithms we have seen so far are comparison sorts: only use comparisons to determine the relative order of elements. • The best worst-case running time that we’ve seen for comparison sorting is O(nlgn). • Is O(nlgn)the best we can do? • Decision treescan help us answer this question. •E.g., insertion sort, merge sort, quicksort, heapsort.
Decision-tree example • Sort 〈a1, a2, …, an〉 Each internal node is labeled i:jfor i, j ∈{1, 2,…, n}. The left subtree shows subsequent comparisons if ai≤aj. The right subtree shows subsequent comparisons if ai≥aj.
Sort 〈a1, a2, a3〉= • 〈9, 4, 6 〉:
Sort 〈a1, a2, a3〉= • 〈9, 4, 6 〉:
Sort 〈a1, a2, a3〉= • 〈9, 4, 6 〉:
Sort 〈a1, a2, a3〉= • 〈9, 4, 6 〉: Each leaf contains a permutation 〈π(1), π(2),…, π(n)〉to indicate that the ordering aπ(1)≤aπ(2)≤...≤aπ(n)has been established.
Decision-tree model • A decision tree can model the execution of any comparison sort: • One tree for each input size n. (there is specific tree for different n values tree is not generic) • View the algorithm as splitting whenever it compares two elements. • The tree contains the comparisons along all possible instruction traces. • The running time of the algorithm =the length of the path taken. • Worst-case running time =height of tree.
Lower bound for decision-tree sorting • Theorem.Any decision tree that can sort n elements must have height Ω(nlgn). Proof.The tree must contain ≥n!leaves, since there are n!possible permutations. • A height-hbinary tree has ≤2hleaves. • Thus, n! ≤2h. • h≥lg(n!)(lgis mono. İncreasing) • ≥lg ((n/e)n)(Stirling’s formula) • = nl(g n–lg e) lg e is constant • = Ω(nlg n) monotonically increasing,increasing if for all x and y such that x ≤ y one has f(x) ≤ f(y), so f preserves the order
Lower bound for comparison sorting Corollary • Heapsort and merge sort are asymptotically optimal comparison sorting algorithms.
Counting Sort Takes time O(k) Takes time O(n) 1 CountingSort(A, B, k) 2 for i=1 to k 3 C[i]= 0; 4 for j=1 to n 5 C[A[j]] += 1; 6 for i=2 to k 7 C[i] = C[i] + C[i-1]; 8 for j=n downto 1 9 B[C[A[j]]] = A[j]; 10 C[A[j]] -= 1; What will be the running time?
Running time • If k= O(n), then counting sort takes Θ(n)time. • But, sorting takes Ω(nlgn) time! Answer: • Comparison sorting takes Ω(nlgn)time. • Counting sort is not a comparison sort. • In fact, not a single comparison between elements occurs!
Why don’t we always use counting sort? • Because it depends on range k of elements • Could we use counting sort to sort 32 bit integers? Why or why not? • Answer: no, k too large (232 = 4,294,967,296)
Stable sorting • Counting sort is a stablesort: it preserves the input order among equal elements.
Dynamic sets Dynamic setsSets that can grow, shrink, or otherwise change over time. • Two types of operations: • queries return information about the set • modifying operations change the set Common queries Search, Minimum, Maximum, Successor, Predecessor Common modifying operations Insert, Delete
Dictionary DictionaryStores a set S of elements, each with an associated key (integer value). OperationsSearch(S, k): return a pointer to an element x in S with key[x] = k, or NIL if such an element does not exist. Insert(S, x): inserts element x into S, that is, S← S⋃ {x} Delete(S, x): remove element x from S
Implementing a dictionary Θ(n) Θ(1) Θ(1) Θ(log n) Θ(n) Θ(n) Θ(1) Θ(1) Θ(1) Hash tableRunning times are average times and assume (simple) uniform hashing and a large enough table (for example, of size 2n) Today Binary search trees
Binary search trees • Binary search trees are an important data structure for dynamic sets. • They can be used as both a dictionary and a priority queue. • They accomplish many dynamic-set operations in O(h) time, where h = height of tree.
= NIL Binary search trees • root of T denoted by root[T] • internal nodes have four fields: key (and possible other satellite data) left: points to left child right: points to right child p: points to parent. p[root[T]] = NIL root[T] Binary tree T 5 3 7 4 8 1
= NIL Binary search trees Keys are stored only in internal nodes! There are binary search trees which store keys only in the leaves … root[T] Binary tree T 5 3 7 4 8 1
5 3 7 4 8 1 Binary search trees • a binary tree is • a leaf or • a root node x with a binary tree as its left and/or right child Binary-search-tree property • if y is in the left subtree of x, then key[y] ≤ key[x] • if y is in the right subtree of x, then key[y] ≥ key[x] Keys don’t have to be unique …
5 1 3 7 3 4 8 1 7 5 8 4 Binary search trees height h = 2 height h = 4 Binary-search-tree property • if y is in the left subtree of x, then key[y] ≤ key[x] • if y is in the right subtree of x, then key[y] ≥ key[x]
5 3 7 4 8 1 Inorder tree walk • binary search trees are recursive structures ➨ recursive algorithms often work well Example: print all keys in order using an inorder tree walk InorderTreeWalk(x) • if x ≠ NIL • then InorderTreeWalk(left[x]) • print key[x] • InorderTreeWalk(right[x]) Correctness: follows by induction from the binary search tree property Running time? Intuitively, O(n) time for a tree with n nodes, since we visit and print each node once.
Inorder tree walk InorderTreeWalk(x) • if x ≠ NIL • then InorderTreeWalk(left[x]) • print key[x] • InorderTreeWalk(right[x]) TheoremIf x is the root of an n-node subtree, then the call InorderTreeWalk(x) takes Θ(n) time. Proof: • T(n) takes small, constant amount of time on empty subtree ➨ T(0) = c for some positive constant c • for n > 0 assume that left subtree has k nodes, right subtree n-k-1 ➨ T(n) = T(k) + T(n-k-1) + d for some positive constant d use substitution method …to show: T(n) = (c+d)n + c ■
Binary-search-tree property 5 k 3 7 4 8 1 ≤ k ≥ k Querying a binary search tree TreeSearch(x, k) • if x = NIL or k = key[x] • then return x • if k < key[x] • then returnTreeSearch(left[x], k) • else returnTreeSearch(right[x], k) Initial call: TreeSearch(root[T], k) • TreeSearch(root[T], 4) • TreeSearch (root[T], 2) Running time: Θ(length of search path) worst caseΘ(h)
Binary-search-tree property k ≤ k ≥ k Querying a binary search tree – iteratively TreeSearch(x, k) • if x = NIL or k = key[x] • then return x • if k < key[x] • then returnTreeSearch(left[x], k) • else returnTreeSearch(right[x], k) IterativeTreeSearch(x, k) • while x ≠ NIL and k ≠ key[x] • do if k < key[x] • then x ← left[x] • else x ← right[x] • return x • iterative version more efficient on most computers
Binary-search-tree property 5 k 3 7 4 8 1 ≤ k ≥ k Minimum and maximum • binary-search-tree property guarantees that • the minimum key is located in the leftmost node • the maximum key is located in the rightmost node TreeMinimum(x) • while left[x] ≠ NIL • do x ← left[x] • return x TreeMaximum(x) • while right[x] ≠ NIL • do x ← right[x] • return x
Binary-search-tree property k ≤ k ≥ k Minimum and maximum • binary-search-tree property guarantees that • the minimum key is located in the leftmost node • the maximum key is located in the rightmost node TreeMinimum(x) • while left[x] ≠ NIL • do x ← left[x] • return x TreeMaximum(x) • while right[x] ≠ NIL • do x ← right[x] • return x Running time? Both procedures visit nodes on a downward path from the root➨ O(h) time
Successor and predecessor • Assume that all keys are distinct Successor of a node xnode y such that key[y] is the smallest key > key[x] We can find y based entirely on the tree structure, no key comparisons are necessary … if x has the largest key, then we say x’s successor is NIL
Successor and predecessor Successor of a node xnode y such that key[y] is the smallest key > key[x] Two cases: • x has a non-empty right subtree➨ x’s successor is the minimum in x’s right subtree • x has an empty right subtree➨ x’s successor y is the node that x is the predecessor of (x is the maximum in y’s left subtree) as long as we move to the left up the tree (move up through right children), we’re visiting smaller keys …
15 6 18 7 17 20 3 2 4 13 9 Successor and predecessor TreeSucessor(x) • if right[x] ≠ NIL • then returnTreeMinimum(right[x]) • y ← p[x] • while y ≠ NIL and x = right[y] • do x ← y • y ← p[x] • return y • Successor of 15? • Successor of 6? • Successor of 4?
15 6 18 7 17 20 3 2 4 13 9 Successor and predecessor TreeSucessor(x) • if right[x] ≠ NIL • then returnTreeMinimum(right[x]) • y ← p[x] • while y ≠ NIL and x = right[y] • do x ← y • y ← p[x] • return y Running time? O(h)
TreeInsert(T, z) y ← NIL x ← root[T] while x ≠ NIL do y ← x if key[z] < key[x] then x ← left[x] else x ← right[x] p[z] ← y if y = NIL then root[T] ← x else if key[z] < key[y] then left[y] ← z else right[y] ← z to insert value v, insert node z with key[z] = v, left[z] = NIL, and right[z] = NIL traverse tree down to find correct position for z Insertion
TreeInsert(T, z) y ← NIL x ← root[T] while x ≠ NIL do y ← x if key[z] < key[x] then x ← left[x] else x ← right[x] p[z] ← y if y = NIL then root[T] ← x else if key[z] < key[y] then left[y] ← z else right[y] ← z to insert value v, insert node z with key[z] = v, left[z] = NIL, and right[z] = NIL traverse tree down to find correct position for z 14 Insertion y z = NIL x y 15 x y 6 18 x y 7 17 20 3 x y 2 4 13 x = NIL 9
TreeInsert(T, z) y ← NIL x ← root[T] while x ≠ NIL do y ← x if key[z] < key[x] then x ← left[x] else x ← right[x] p[z] ← y if y = NIL then root[T] ← z else if key[z] < key[y] then left[y] ← z else right[y] ← z Running time? to insert value v, insert node z with key[z] = v, left[z] = NIL, and right[z] = NIL traverse tree down to find correct position for z 14 Insertion 15 6 18 7 17 20 3 y 2 4 13 z 9 O(h)
Deletion • we want to delete node z TreeDelete has three cases: • z has no children ➨ delete z by having z’s parent point to NIL, instead of to z 15 6 18 9 20 3 7
Deletion • we want to delete node z TreeDelete has three cases: • z has no children ➨ delete z by having z’s parent point to NIL, instead of to z • z has one child ➨ delete z by having z’s parent point to z’s child, instead of to z 15 6 18 9 20 3 7
Deletion • we want to delete node z TreeDelete has three cases: • z has no children ➨ delete z by having z’s parent point to NIL, instead of to z • z has one child ➨ delete z by having z’s parent point to z’s child, instead of to z • z has two children ➨ z’s successor y has either no or one child ➨ delete y from the tree and replace z’s key and satellite data with y’s 15 6 18 9 20 3 7
Deletion • we want to delete node z TreeDelete has three cases: • z has no children ➨ delete z by having z’s parent point to NIL, instead of to z • z has one child ➨ delete z by having z’s parent point to z’s child, instead of to z • z has two children ➨ z’s successor y has either no or one child ➨ delete y from the tree and replace z’s key and satellite data with y’s Running time? 15 7 18 9 20 3 O(h)
Minimizing the running time • all operations can be executed in time proportional to the height h of the tree (instead of proportional to the number n of nodes in the tree) Worst case: Solution: guarantee small height (balance the tree) ➨ h = Θ(log n) Next week: several schemes to balance binary search trees Θ(n)
Balanced binary search trees Advantages of balanced binary search trees over linked lists efficient search in Θ(log n) time oversorted arrays efficient insertion and deletion in Θ(log n) time overhash tables can find successor and predecessor efficiently in Θ(log n) time
Implementing a dictionary balanced binary search trees ➨height is Θ(log n) Θ(n) Θ(1) Θ(1) Θ(log n) Θ(n) Θ(n) Θ(1) Θ(1) Θ(1) Θ(height) Θ(height) Θ(height)