基本工具类(所有对象实现Comparable接口)
public class Basic {
public static boolean less(Comparable a,Comparable b) {
return a.compareTo(b) < 0;
}
public static void exchange(Comparable[] a,int i,int j) {
Comparable t = a[i];
a[i]=a[j];
a[j]=t;
}
public static void shuffle(Comparable[] a){
//打乱数组,消除对输入的依赖
List<Comparable> list = Arrays.asList(a);
Collections.shuffle(list);
a = list.toArray(a);
}
}
less()用于比较两个对象的大小;
exchange()用于交换数组中制定的两个对象;
shuffle()用于打乱数组,消除对输入的依赖;
快速排序类
public class Quick {
private static int partition(Comparable[] a,int start,int end){
int i = start;
int j = end + 1;
Comparable v = a[i];
while(true){
while(Basic.less(a[++i], v)) if(i==end) break;
while(Basic.less(v, a[--j]));
if(i>=j) break;
Basic.exchange(a, i, j);
}
Basic.exchange(a,start,j);
return j;
}
public static void sort(Comparable[] a){
Basic.shuffle(a);
sort(a, 0, a.length-1);
}
public static void sort(Comparable[] a,int start,int end){
if(start>=end)return;
int contact = partition(a, start, end);
sort(a, start, contact-1);
sort(a, contact+1, end);
}
}
测试类
import java.util.ArrayList;
import java.util.List;
public class TestSort implements Comparable<TestSort> {
public char c;
public TestSort(char c) {
this.c=c;
}
@Override
public int compareTo(TestSort o) {
if(this.c<o.c){
return -1;
}else if(this.c==o.c) {
return 0;
}else {
return 1;
}
}
public static void main(String[] args){
String string = "zxcvbnmadhewijdijskiaqnhkjajndlsiqpoioweiu";
char[] chars = string.toCharArray();
List<TestSort> tList = new ArrayList<TestSort>();
for(char c:chars){
tList.add(new TestSort(c));
}
TestSort[] tSorts = tList.toArray(new TestSort[tList.size()]);
Quick.sort(tSorts);
for(int i=0;i<tSorts.length;i++){
System.out.print(tSorts[i].c);
}
}
}
排序结果
aaabcdddeehhiiiiiijjjjkklmnnnoopqqssuvwwxz