QuickSort 快速排序 基于伪代码实现

时间:2024-01-19 10:56:56

本文原创,转载请注明地址 http://www.cnblogs.com/baokang/p/4737492.html

伪代码

 quicksort(A, lo, hi)
if lo < hi
p = partition(A, lo, hi)
quicksort(A, lo, p - 1)
quicksort(A, p + 1, hi) partition(A, lo, hi)
pivot = A[hi]
i = lo //place for swapping
for j = lo to hi - 1
if A[j] <= pivot
swap A[i] with A[j]
i = i + 1
swap A[i] with A[hi]
return i

Java实现

     public void quickSort(int[] a,int lo, int hi){
if(lo<hi){
int p=partition(a, lo, hi);
quickSort(a,lo,p-1);
quickSort(a, p+1, hi);
}
}
public int partition(int[] a,int lo, int hi){
int i,j,privot;
privot=a[hi];
i=lo;
for(j=lo;j<=hi-1;j++){
if(a[j]<privot){
swap(a, i, j);
i++;
}
}
swap(a,i,hi);
return i;
}
public void swap(int[] a,int lo,int hi){
int s=a[lo];
a[lo]=a[hi];
a[hi]=s;
}