Description of quicksortQuicksort, like merge sort, is based on the divide-and-conquer paradigm introduced in Section 1.3.1. Here is the three-step divide-and-conquer process for sorting a typical subarray A[p . . r]. To sort an entire array A, the initial call is QUICKSORT(A, 1, length[A]). The key to the algorithm is the PARTITION procedure, which rearranges the subarray A[p . . r] in place.
以下是java代码:
public class quickSort {
void qs(int[] a,int q,int r){
int i=q,j=r,x,temp;
x=a[q];
if(q>=r) return;
while(true){
while(a[i]<x) i++;
while(a[j]>x) j--;
if(i<j){
temp=a[i];a[i]=a[j];a[j]=temp;
j--;
i++;
}
else break;
}
qs(a,q,j);
qs(a,j+1,r);
}
public static void main(String argvs[]){
quickSort q=new quickSort();
int a[]={5,3,2,6,4,1,3,7};
q.qs(a,0,a.length);
for(int i=0;i<8;i++)
System.out.print(a[i]+" ");
}
}
Divide: The array A[p . . r] is partitioned (rearranged) into two nonempty subarrays A[p . . q] and A[q + 1 . . r] such that each element of A[p . . q] is less than or equal to each element of A[q + 1 . . r]. The index q is computed as part of this partitioning procedure.
Conquer: The two subarrays A[p . . q] and A[q + 1 . . r] are sorted by recursive calls to quicksort.
Combine: Since the subarrays are sorted in place, no work is needed to combine them: the entire array A[p . . r] is now sorted.
The following procedure implements quicksort.
QUICKSORT(A,p,r)
1 if p < r
2 then q = PARTITION(A,p,r)
3 QUICKSORT(A,p,q)
4 QUICKSORT(A,q + 1,r)
Partitioning the array
PARTITION(A,p,r)
1 x =A[p]
2 i = p - 1
3 j = r + 1
4 while TRUE
5 do repeat j = j - 1
6 until A[j] <= x
7 repeat i = i + 1
8 until A[i] >= x
9 if i < j
10 then exchange A[i] and A[j]
11 else return j