以划分后第一个元素为基准值的快排:
private static void quickSort(int a[],int l,int r){
if(lint i=l,j=r,index=a[l];
while(iwhile(i=index){
j--;
}
if(iwhile(iif(i1);
quickSort(a,i+1,r);
}
}
以划分后最后一个元素为基准的快排:
private static void quickSort1(int a[],int l,int r){
if(lint i=l,j=r,index=a[r];
while(iwhile(iif(iwhile(i=index){
j--;
}
if(i1);
quickSort(a,i+1,r);
}
}
想改成以中位数为基准,于是改成了这样:
private static void quickSort2(int a[],int l,int r){
if(lint i = l, j = r, mid = (l+r)/2;
int index = a[mid];
while(i < j) {
while(i < j && a[j] > index) {
j--;
}
while(i < j && a[i] < index) {
i++;
}
if(i < j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
System.out.println(i+" "+j+" "+mid);
quickSort2(a,l,i - 1);
quickSort2(a, i + 1, r);
}
但问题是,数组中有任何一个重复元素,就会陷入死循环
重新换一种思路,即用以最后元素为基准的代码,只需要将中间数和最后数互换即可:
private static void quickSort2(int a[],int l,int r){
if(l2);
int index = a[r];
int p = l;
for(int i = l; i < r; i++) {
if(a[i] < index) {
swap(a, p, i);
p++;
}
}
swap(a, p, r);
quickSort2(a,l,p - 1);
quickSort2(a, p + 1, r);
}
}
private static void swap(int a[], int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
以随机数为基准也同样:
private static void quickSort2(int a[],int l,int r){
if(ldouble ran = Math.random();
swap(a, r, (int)(ran*(r - l) + l));
int index = a[r];
int p = l;
for(int i = l; i < r; i++) {
if(a[i] < index) {
swap(a, p, i);
p++;
}
}
swap(a, p, r);
quickSort2(a,l,p - 1);
quickSort2(a, p + 1, r);
}
}
private static void swap(int a[], int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
通常递归都可以用栈模拟,代码如下:
class range {
int l;
int r;
public range(int l, int r) {
this.l = l;
this.r = r;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i stk = new Stack<>();
stk.push(new range(0, n - 1));
while(!stk.isEmpty()) {
range ran = stk.pop();
int l = ran.l;
int r = ran.r;
int p = quick(a, l, r);
if(p != -1) {
stk.push(new range(l, p - 1));
stk.push(new range(p + 1, r));
}
}
for(int i=0;i1;i++){
System.out.print(a[i]+" ");
}System.out.println(a[n-1]);
}
public static int quick(int a[], int l, int r) {
if(ldouble ran = Math.random();
swap(a, r, (int)(ran*(r - l) + l));
int index = a[r];
int p = l;
for(int i = l; i < r; i++) {
if(a[i] < index) {
swap(a, p, i);
p++;
}
}
swap(a, p, r);
return p;
}
return -1;
}
private static void swap(int a[], int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
虽然看着复杂了一些,但本质没变