package qinglin.learn.arithmetic;
public class QuickSort
{
public static void quickSort(int[] a)
{
qSort(a, 0, a.length - 1);
}
/**
* 对下标从s到t的元素进行快速排序。
*/
public static void qSort(int[] a, int s, int t)
{
if (s < t)
{
int pivot = partition(a, s, t);
qSort(a, s, pivot - 1);
qSort(a, pivot + 1, t);
}
}
/**
* 该方法返回枢纽的下标。
*/
public static int partition(int[] a, int p, int r)
{
int i = p, j = r + 1;
int x = a[p];
/**
* 将 >= x的元素交换到右边区域,<= x的元素交换到左边区域。
*/
while (true)
{
while (a[++i] < x)
{
if (i >= r)
break;
}
while (a[--j] > x)
;
if (i >= j)
break;
swap(a, i, j);
}
a[p] = a[j];
a[j] = x;
return j;
}
public static void swap(int []a,int i,int j)
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
public static void main(String[] args) throws Exception
{
int[] a = new int[]{3,25,45,2,7,8,100,90,76};
quickSort(a);
// 输出排序后的数组元素。
for (int i = 0; i < a.length; i++)
System.out.print(a[i]+" ");
}
}
快速排序
最新推荐文章于 2024-07-17 10:35:12 发布