全部博文(136)
分类: C/C++
2011-03-15 09:12:25
When this process is finished, the array is in order.
Quicksort is fast because once an element is known to be less than the pivot value, we don't have to compare it to any of the big ones; similarly, big ones are not compared to little ones. This makes it much faster than the simple sorting methods such as insertion sort and bubble sort that compare each element directly to all the others.
The swap operation, which interchanges two elements, appears three times in quicksoft, so it is best made into a separate function:
(1) Partitioning selects a random element as the pivot, swaps it temporarily to the front, then sweeps through the remaining elements, exchanging those smaller than the pivot ("little ones") towards the beginning (at location last) and big ones towards the end (at location i) At the beginning of the process, just after the pivot has been swapped to the front, last=0 and elements i=1 through n-1 are unexamined.
(2) At the top of the for loop, element 1 through last are strictly less than the pivot, elements last+1 through i-1 are greater than or equal to the pivot, and element i through n-1 have not been examined yet. Until v[i]>=v[0], the algorithm may swap v[i] with itself; this wastes some time but not enough to worry about.
(3) After all elements have been partitioned, element 0 is swapped with the last element to put the pivot element in its final position; this maintains the correct ordering.
(4) The same process is applied to the left and right sub-arrays; when this has finished, the whole array has been sorted.
How fast is quicksort? In the best possible case,
This goes on for about log2 n levels, so the total amount of work in the best case is proportional to n+2× n/2+4× n/4+8× n/8 … (log2 n terms), which is nlog2 n. On the average, it does only little more work. It is customary to use base 2 logarithms; thus we say that quicksort takes time proportional to nlog n.