/*
* 快速排序算法是C.A.R.Hoare于1962年提出的一种划分交换的算法,它采用分治法进行排序。
* 其基本思想是任取待排序远元素序列中的某个元素(例如取第一个元素)作为基准,按照该元素的排
* 序码的大小,将整个元素序列划分为左右两个字序列,左侧子序列中所有元素都小于基准元素的排序
* 码,右侧子序列中所有元素的排序码都大于或等于基准元素的排序码,基准元素则排在这两个子序列
* 中间(这也是该元素最终安放的位置)。然后分别对两个子序列重复上述方法,直到所有元素都排在
* 相应的位置上为止。
*/
public class QuitSort<E extends Comparable<E>>
{
private E[] elementArray;
private int length;
QuitSort(E[] array)
{
elementArray = array;
length = elementArray.length;
}
public int divide(int low,int high)
{
int position = low;
for(int i=low+1;i<=high;i++)
{
if(elementArray[i].compareTo(elementArray[low])<0)
{
position++;
if (position!=i)
{
E temp = elementArray[i];
elementArray[i] = elementArray[position];
elementArray[position] = temp;
}
}
}
//将array[low]插到中间
E temp = elementArray[low];
elementArray[low] = elementArray[position];
elementArray[position] = temp;
return position;
}
public void sort()
{
quickSort(0, length-1);
}
public void quickSort(int left,int right)
{
int midPosition = divide(left, right);
if (left<midPosition-1)quickSort(left, midPosition-1);
if ((midPosition+1)<right) quickSort(midPosition+1,right);
}
public void print()
{
for (int i = 0; i < elementArray.length; i++)
{
System.out.println(elementArray[i]);
}
}
}
Example for the model:
Integer[] array2 = {3,6,1,9,2,7,21,8,56};
QuitSort<Integer> test2 = new QuitSort<Integer>(array2);
test2.sort();
test2.print();
Result of the Example:
1
2
3
6
7
8
9
21
56