快速排序是一种利用分区的思想来实现的一个不错的排序算法, 在弄懂快排之前,还得先弄清楚分区(partition)是怎么弄的。
对于给定的数组a,我们从中选择一个值作为中心点(pivot);
定义两个索引变量分别leftScan,rightScan分别指向数组a的第一个元素和最后一个元素;
定义一个while循环
leftScan从左向右扫描直到a[leftScan]>pivot;
rightScan从右向左扫描直到a[rightScan]<pivot;
如果leftScan>=rightScan,break退出循环
否则,交换a[leftScan]和a[rightScan],然后继续循环;
最后会返回leftScan最为pivot的索引。
这样一趟下来 , 就把给定的数组分成以pivot为中心的两个区,pivot左边的是小于pivot的,pivot右边的是大于pivot的。
public class ArrayParti { private long[] a; private int nElement; public ArrayParti(int max) { a = new long[max]; nElement = 0; } public int partition(int left,int right,long pivot){ int leftParti = left-1; int rightParti = right+1; while(true){ while(leftParti<right && a[++leftParti]<pivot); while(rightParti>left && a[--rightParti]>pivot); if(leftParti>=rightParti)break; else swap(leftParti,rightParti); } System.out.println("pivot index is:"+leftParti); return leftParti; } private void swap(int one, int two) { long temp; temp = a[one]; a[one]=a[two]; a[two]=temp; } public void insert(long v){ a[nElement]=v; nElement++; } public void display(){ for(int i=0;i<a.length;i++){ System.out.print(a[i]+"\t"); } System.out.print("\n"); } }
2.递归实现快速排序
1)数组a中选一个element作为pivot
2)根据选定的pivot给数组分区,左边的都比pivot小,右边的都比pivot大
3)对pivot左边的数据和pivot右边的数据分别递归实现上面的步骤。
public class ArrayQuick1 { private long[] a; private int nElement; public ArrayQuick1(int max) { a = new long[max]; nElement = 0; } public void sort(){ quickSort(0,nElement-1); } private void quickSort(int left, int right) { if(left-right>=0){ return; }else{ long pivot = a[right]; int partition = partition(left,right,pivot); quickSort(left,partition-1); quickSort(partition+1,right); } } private int partition(int left, int right, long pivot) { int leftParti = left-1; int rightParti = right; while(true){ while(a[++leftParti]<pivot); while(rightParti>0 && a[--rightParti]>pivot); if(leftParti>=rightParti)break; else swap(leftParti,rightParti); } swap(leftParti,right); return leftParti; } private void swap(int one, int two) { long temp; temp = a[one]; a[one]=a[two]; a[two]=temp; } public void insert(long v){ a[nElement]=v; nElement++; } public void display(){ for(int i=0;i<a.length;i++){ System.out.print(a[i]+"\t"); } System.out.print("\n"); } }