快速排序是一种不稳定排序。平均时间复杂度0(nlogn)。升序(降序)排序:每次选取一个基准数,先从后遍历直至遇到比基准数小(大)的数,则将该数与基准数的位置对调,并将该数位置视为下次置换的位置。再从前遍历直至遇到比基准数大(小)的数,则将该数置换到上次置换数的位置。直至从前遍历和从后遍历都到达同一位置,即找到基准数的位置,再将基准数替换位置的数即可。再对基准数左右的两个子集迭代该方法,即可完成整个排序。
public class QuickSort
{
public QuickSort(){}
public static int[] sort(int[] array,int start, int end, String rule)
{
if(!rule.equalsIgnoreCase("increase") && !rule.equalsIgnoreCase("decrease"))
{
System.out.println("Please input the right define of rule: [increase] or [decrease]!");
System.exit(-1);
}
int[] arraySorted = array.clone();
if(start<end)
{
int i=start;
int j=end;
int temp = arraySorted[start];
if(rule.equalsIgnoreCase("increase"))
{
while(i<j)
{
while(i<j && arraySorted[j]>=temp) j--;
if(i<j) arraySorted[i++] = arraySorted[j];
while(i<j && arraySorted[i]<=temp) i++;
if(i<j) arraySorted[j--] = arraySorted[i];
}
}
else if(rule.equalsIgnoreCase("decrease"))
{
while(i<j)
{
while(i<j && arraySorted[j]<=temp) j--;
if(i<j) arraySorted[i++] = arraySorted[j];
while(i<j && arraySorted[i]>=temp) i++;
if(i<j) arraySorted[j--] = arraySorted[i];
}
}
arraySorted[i] = temp;
arraySorted = sort(arraySorted,start,i-1,rule);
arraySorted = sort(arraySorted,i+1,end,rule);
}
return arraySorted;
}
private static void print(int[] array)
{
for(int i=0;i<array.length;i++)
{
System.out.print(array[i]+" ");
}
System.out.println();
}
public static void main(String[] args)
{
int[] array = new int[]{1,10,3,5,2,4,9,11};
int[] arraySort = sort(array,0,array.length-1,"increase");
System.out.println("Before sort:");
print(array);
System.out.println("After sort:");
print(arraySort);
}
}