partiton
1.在数组a[]找到一个枢纽元(pivot),pivot与第一个元素交换
2.a[low]为第二个元素,a[high]为倒数第一个元素
3.当low元素小于pivot,low++,当high元素大于pivot,high++,当i,j都停止自增时,若a[i]在a[j]左侧,则交换元素
4.当a[low]在a[high]右侧,停止
5.当high>first且A[high]>=pivot时,high--
6.当a[high] < pivot,交换,返回high,否则返回first
partition代码
public int partition(int[] A, int first, int last){
//确定一个pivot,左边小于,右边大于
//区间第一个元素为pivot
int pivot = A[first];
int low = first + 1;
int high = last;
while (low < high){
if(low < high && A[low] <= pivot){
low++;
}
if(low < high && A[high] > pivot){
high--;
}
if(low < high){
int temp = A[high];
A[high] = A[low];
A[low] = temp;
}
}
while (high > first && A[high] >= pivot){
//查找结束时A[high]等于主元或查找不执行时只有两个元素
high--;
}
if(pivot > A[high]){
A[first] = A[high];
A[high] = pivot;
return high;
}
return first;
}
整体代码
public int[] quickSort(int[] A, int n){
sort(A, 0, n - 1);
return A;
}
public void sort(int[] A, int first, int last){
if (first < last){
int partition = partition(A, first, last);
sort(A, first, partition - 1);
sort(A, partition+1, last);
}
}
public int partition(int[] A, int first, int last){
//确定一个pivot,左边小于,右边大于
//区间第一个元素为pivot
int pivot = A[first];
int low = first + 1;
int high = last;
while (low < high){
if(low < high && A[low] <= pivot){
low++;
}
if(low < high && A[high] > pivot){
high--;
}
if(low < high){
int temp = A[high];
A[high] = A[low];
A[low] = temp;
}
}
while (high > first && A[high] >= pivot){
//查找结束时A[high]等于主元或查找不执行时只有两个元素
high--;
}
if(pivot > A[high]){
A[first] = A[high];
A[high] = pivot;
return high;
}
return first;
}
emmm,影响性能的主要是partition代码,等慢慢学习后会继续修改