这是递归版本
package quicksort;
/**
* 快速排序
* 也是分成两个数组,跟中间的数进行比较,左边得都小于等于中间数,且小于等也右边的数,右边的数大于等于中间的数
* 思路是让数组的第一个到倒数第二个数与最后一个数进行比较
* 若<=最后一个数,则i++,且交换array[i]与array[j];反之,什么也不做
* 最后循环完后交换array[i+1]与数组最后一个数
*/
public class QuickSort
{
public void quicksort(int[] array,int from,int to)
{
if(from<to){ //条件很重要
int x = array[to];
int i = from-1;
for (int j = from; j < to; j++)
{
if (array[j]<=x)
{
i++;
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
//交换x与array[i+1];
array[to] = array[i+1];
array[i+1] = x;
quicksort(array,from,i);
quicksort(array,i+1,to);
}
}
public static void main(String[] args)
{
QuickSort quickSort = new QuickSort();
int [] a = new int[]{5,1,4,2,3};
quickSort.quicksort(a,0,a.length-1);
for(int i : a)
{
System.out.print(i+" ");
}
}
}