100 likes | 203 Views
Improving Quicksort. Quicksort stack size. Each tree element is the partitioning element The tree structure does not change with the order of partitioning However, to traverse the tree the size of the stack may grow significantly in degenerate cases. Quicksort stack size.
E N D
Quicksort stack size • Each tree element is the partitioning element • The tree structure does not change with the order of partitioning • However, to traverse the tree the size of the stack may grow significantly in degenerate cases
Quicksort stack size • Stack size for 2 random cases and for one degenerate
Quicksort stack size Naïve quicksort implementation similar to preorder traversal private void traverseS(Node h) { NodeStack s = new NodeStack(max); s.push(h); while (!s.empty()) { h = s.pop(); h.item.visit(); if (h.r != null) s.push(h.r); if (h.l != null) s.push(h.l); } }
Quicksort stack size Naïve case - preorder Stack output A - CB A CED B CEGF D CEGIH F …. Visit the smallest sub-tree first Stack output A - BC A B C DE B D E FG D ….
Quicksort stack size (modified book code) static void quicksort(ITEM[] a, int l, int r) { intStack S = new intStack(50); S.push(l); S.push(r); while (!S.empty()) { r = S.pop(); l = S.pop(); if (r <= l) continue; int i = partition(a, l, r); if (i-l > r-i) { S.push(l); S.push(i-1); S.push(i+1); S.push(r);} else { S.push(i+1); S.push(r); S.push(l); S.push(i-1); } } }
Small input • It is guaranteed that a recursive sorting method will be called many times with a small input • Goal: become efficient for small inputs • Recursions can be an overhead for small input and do not offer much gain • Observation: insert sort can be efficient for small inputs
Small input • Code modifications • Call insert sort when small input if (r-l <= M) insertion(a, l, r); • Leave unsorted (temporarily) if (r-l <= M) return; A partially sorted input will be created O(N) for insert sort
Small input • Experimental decision of cutoff threshold M