public class QuickSort {
static void qSort(int[] a, int p, int r){
if (p < r)
{
int q = partition(a, p,r);
qSort ( a,p,q-1 );
qSort ( a,q+1,r );
}
}
static int partition(int[] a,int p,int r){
int i=p;
int j = r+1;
int x = a[p];
while (true){
while ((a[++i] - x < 0) && (i < r)); //(a[++i] - x < 0)条件不成立即表示a[i]与x相等或者在x的右边
while (a[--j] - x > 0 ); //结束即表示a[j]在x的左边或者相等
if (i >= j) break;
swap(a,i,j);
}
a[p] = a[j];
a[j] = x; //因为a[j]比x小,所以更新x和a[j]
return j;
}
static void swap (int[] a, int i, int j) {
int temp = 0;
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
public static void main (String[] args) {
int[] a = {12,45,5,78,23};
qSort ( a,0,a.length-1 );
for (int i = 0; i < a.length; i++)
{
System.out.print (a[i]+" ");
}
}
}
快速排序递归实现
于 2019-06-16 18:18:33 首次发布