Improving Quicksort Quicksort stack size Each tree element
- Slides: 9
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 • Stack size for 2 random cases and for one degenerate
Quicksort stack size Naïve quicksort implementation similar to preorder traversal private void traverse. S(Node h) { Node. Stack s = new Node. Stack(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 Visit the smallest sub-tree first Stack output A - CB A BC A CED B B C CEGF D DE B CEGIH F D E FG D ….
Quicksort stack size (modified book code) static void quicksort(ITEM[] a, int l, int r) { int. Stack S = new int. Stack(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