package ls.algorithm.sort;
import java.util.Stack;
public class QuickSort extends SortInf{
public QuickSort(int size) {
super(size);
// TODO Auto-generated constructor stub
}
@Override
public void sort() {
// TODO Auto-generated method stub
printSrcArr();
Stack s = new Stack();
s.push(0);
s.push(arr.length-1);
while(!s.empty())
{
int right=s.pop();
int left=s.pop();
if(left < right) {
int midPos= partitionSort(left,right);
if(left < midPos-1) {
s.push(left);
s.push(midPos-1);
}
if(midPos+1 < right) {
s.push(midPos+1);
s.push(right);
}
}
}
printSrcArr();
}
private int partitionSort(int left,int right)
{
int pivot = arr[left];
while (left < right) {
while (left < right && arr[right] >= pivot) {
right--;
}
arr[left] =arr[right];
while (left < right && arr[left] <= pivot) {
left++;
}
arr[right] = arr[left];
}
arr[left] = pivot;
return left;
}
}
生成需排序序列的抽象类
package ls.algorithm.sort;
import java.util.Random;
public abstract class SortInf {
int[] arr;
public SortInf(int size)
{
arr=new int[size];
for(int i=0;i
{
arr[i]=new Random().nextInt(50);
}
}
public void printSrcArr()
{
System.out.print("数组:");
for(int i=0;i
{
System.out.print(arr[i]+" ");
}
System.out.print("\n");
}
public abstract void sort();
}