最近刷题遇到she’ll排序问题,通过Debug调试观察排序过程。记录下~
package sort;
public abstract class Sort<T extends Comparable<T>> {
// 排序算法ADT
public abstract void sort(T[] nums);
protected boolean less(T v, T w) {
return v.compareTo(w) < 0;
}
protected void swap(T[] a, int i, int j) {
T t = a[i];
a[i] = a[j];
a[j] = t;
}
}
she’ll排序算法实现
package sort;
public class ShellSort<T extends Comparable<T>> extends Sort<T>{
@Override
public void sort(T[] nums) {
int N = nums.length;
int h = 1;
while(h < N/3)
h = 3 * h + 1;
while(h >= 1) {
for(int i = h; i < N; i++) {
for(int j = i; j >=h && less(nums[j], nums[j - h]); j -= h) {
swap(nums, j, j - h);
}
}
h /=3;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Character[] ls = {'S', 'H', 'E', 'L', 'L', 'S', 'O', 'R', 'T', 'E', 'X', 'A', 'M', 'P', 'L', 'E'};
ShellSort<Character> s = new ShellSort<Character>();
s.sort(ls);
for(Character i : ls) {
System.out.println(i.toString());
}
}
}