基本工具类(所有对象实现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;
}
}
less()用于比较两个对象的大小;
exchange()用于交换数组中制定的两个对象;
希尔排序类
public class Shell {
public static void sort(Comparable[] a){
int h = 1;
while(h<a.length/3)h=h*3+1;
while(h>=1){
for(int i=0;i<h;i++){
for(int j=i+h;j<a.length;j+=h){
for(int k=j;k>=i+h && Basic.less(a[k], a[k-h]);k-=h){
Basic.exchange(a, k, k-h);
}
}
}
h=h/3;
}
}
}
测试类
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()]);
Shell.sort(tSorts);
for(int i=0;i<tSorts.length;i++){
System.out.print(tSorts[i].c);
}
}
}
排序结果
aaabcdddeehhiiiiiijjjjkklmnnnoopqqssuvwwxz