思想:快速排序,关键为划分 (1)定轴值:直接使用第一个值;也可使用三点中值法进行优化。 (2)指针移动:可以使用单向扫描,也可以使用双向扫描法。 代码如下:
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class QuickSort {
public static int partition(int[] a,int st,int end){
int target=a[st];
int sp=st+1;
while (sp<=end){
if (a[sp]<=target) sp++;
else {
int temp=a[sp];
a[sp]=a[end];
a[end]=temp;
end--;
}
}
a[st]=a[end];
a[end]=target;
return end;
}
public static void quicksort(int[] a,int st,int end){
if (st<end) {
int p = partition(a, st, end);
quicksort(a, st, p - 1);
quicksort(a, p + 1, end);
}
}
public static int partition1(int[] a,int st,int end){
int mid=st+((end-st)>>1);
int midvalue=-1;
if ((a[st]<=a[mid]&&a[st]>=a[end])||(a[st]>=a[mid]&&a[st]<=a[end])){
midvalue=st;
}else if ((a[mid]<=a[st]&&a[mid]>=a[end])||(a[mid]>=a[st]&&a[mid]<=a[end])){
midvalue=mid;
}else {midvalue=end;}
if (st!=midvalue){
int temp = a[st];
a[st] = a[midvalue];
a[midvalue] = temp;
}
int target=a[st];
int sp=st+1;
boolean flag1=false;
boolean flag2=false;
while (sp<=end){
if (a[sp]<=target) sp++;
else flag1=true;
if (a[end]>target)end--;
else flag2=true;
if (flag1&&flag2){
int temp=a[sp];
a[sp]=a[end];
a[end]=temp;
sp++;
end--;
flag1=false;
flag2=false;
}
}
a[st]=a[end];
a[end]=target;
return end;
}
public static void quicksort1(int[] a,int st,int end){
if (st<end) {
int p = partition1(a, st, end);
quicksort1(a, st, p - 1);
quicksort1(a, p + 1, end);
}
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("请输入数组的长度");
int len=scanner.nextInt();
int[] a=new int[len];
for (int i = 0; i <len ; i++) {
a[i]=new Random().nextInt(20);
}
int[] b=Arrays.copyOf(a,a.length);
System.out.println(Arrays.toString(a));
quicksort(a,0,len-1);
System.out.println(Arrays.toString(a));
System.out.println("--------------");
quicksort1(b,0,len-1);
System.out.println(Arrays.toString(b));
}
}
|