1 / 9

Improving Quicksort

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.

africa
Download Presentation

Improving Quicksort

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Improving Quicksort

  2. 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

  3. Quicksort stack size • Stack size for 2 random cases and for one degenerate

  4. 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); } }

  5. 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 ….

  6. 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); } } }

  7. 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

  8. 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

  9. Small input • Experimental decision of cutoff threshold M

More Related