title: 快速排序实现代码
date: 2019-06-11 21:17:47
tags:
快速排序代码:
其中insertionSort
插入排序可以使用副任意简单的排序算法
public class QuickSort <AnyType extends Comparable<? super AnyType>>{
private final static int CUTOFF = 4;
public static <AnyType extends Comparable<? super AnyType>>AnyType median(AnyType [] a,int left, int right) {
int center = (left+right)>>1;
if(a[left].compareTo(a[center])>0) {
change(a,left,center);
}if(a[left].compareTo(a[right])>0) {
change(a,right,left);
}if(a[right].compareTo(a[center])<0) {
change(a,right,center);
}
change(a,center,right-1);
return a[right -1];
}
public static <AnyType extends Comparable<? super AnyType>>AnyType[] change(AnyType [] a,int i,int j) {
AnyType b = a[i];
a[i] = a[j];
a[j] = b;
return a;
}
public static <AnyType extends Comparable<? super AnyType>>AnyType[] Sort(AnyType [] a,int left ,int right) {
if(left+CUTOFF<=right) {
AnyType pivot = median(a,left,right);
int i = left;
int j = right-1;
while (true){
while(a[++i].compareTo(pivot)<0) {}
while(a[--j].compareTo(pivot)>0) {}
if(i<j) {
change(a,i,j);
}else{break;}
}
change(a,i,right-1);
Sort(a,left,i-1);
Sort(a,i+1,right);
return a;
}else {
insertionSort(a,left,right);
return a;
}
}
public static <AnyType extends Comparable<? super AnyType>>AnyType[] insertionSort(AnyType[] a,int left,int right) {
int j;
for(int i = left+1;i<=right;i++) {
AnyType tmp = a[i];
for(j = i;j>left&&tmp.compareTo(a[j-1])<0;j--) {
a[j] = a[j-1];
}
a[j] = tmp;
}
return a;
}