views:

82

answers:

1

Hi, I am trying to understand exactly what this method does, it say its suppose to "Keep swapping the outer-most wrongly-positioned pairs". I put this into a program and tried different array but the result make no sense to me, what exactly does this do

partition(A, p)  
A: array of size n, p: integer s.t. 0 <= p < n

 1. swap(A[0],A[p])

 2. i <- 1, j <- n − 1

 3. while i < j do

 4.   while A[i] <= A[0] and i < n do

 5.     i <- i + 1

 6.   while A[j] > A[0] and j > 0 do

 7.     j <- j − 1

 8.   if i < j then

 9.     swap(A[i], A[j])

10. swap(A[0], A[j])

11. return j
+1  A: 

The algorithm this pseudocode implements is the partitioning phase of the quicksort sorting algorithm. It will arrange the array so that all values smaller than or equal to A[p] are at the left and all larger values at the right. It returns the index j that is the last index of the left side for which A[j] equals A[p].

If you are not familiar with quicksort, the intent is to use this partition algorithm to split the array into "small" and "large" parts and recursively sort each part. Since the small ones had been arranged to come before the large ones in the array, the array gets sorted. If p is picked appropriately so that A[p] is close to the middle of the values in A, this is a very fast sorting method.

jk
thanks for the reply
Shellscriptbeginner