11.07.2015 Views

Advanced Programming Guide

Advanced Programming Guide

Advanced Programming Guide

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

6 • Chapter 2: Procedures, Variables, and Extending MapleThe Quick-Sort AlgorithmSorting a few numbers is quick using any method, but sorting largeamounts of data can be very time consuming; thus, finding efficient methodsis important.The following quick-sort algorithm is a classic algorithm. The key tounderstanding this algorithm is to understand the operation of partitioning.This involves choosing any one number from the array that you areabout to sort. Then, you reposition the numbers in the array that are lessthan the number that you chose to one end of the array and repositionnumbers that are greater to the other end. Lastly, you insert the chosennumber between these two groups.At the end of the partitioning, you have not yet entirely sorted thearray, because the numbers less than or greater than the one you chosemay still be in their original order. This procedure divides the array intotwo smaller arrays which are easier to sort than the original larger one.The partitioning operation has thus made the work of sorting much easier.You can bring the array one step closer in the sorting process bypartitioning each of the two smaller arrays. This operation produces foursmaller arrays. You sort the entire array by repeatedly partitioning thesmaller arrays.ExampleThe partition procedure uses an array to store the list because you canchange the elements of an array directly. Thus, you can sort the array inplace and not waste any space generating extra copies.The quicksort procedure is easier to understand if you look at theprocedure partition in isolation first. This procedure accepts an arrayof numbers and two integers. The two integers are element numbers of thearray, indicating the portion of the array to partition. While you couldpossibly choose any of the numbers in the array to partition around, thisprocedure chooses the last element of the section of the array for thatpurpose, namely A[n]. The intentional omission of global and localstatements shows which variables Maple recognizes as local and whichare global by default. It is recommended, however, that you not makethis omission in your procedures.> partition := proc(A::array(1, numeric),> m::posint, n::posint)> i := m;> j := n;> x := A[j];> while i if A[i]>x then

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!