public class Selection{
// 将数组a按升序排列
public static void sort(Comparable[] a){
int N = a.length;
for(int i = 0; i < N; i++){
int min = i;
for(int j = i + 1; j < N; j++){
if(less(a[j], a[min])){
min = j;
}
exch(a, i, min);
}
}
}
// 数组两个元素比较
private static boolean less(Comparable v, Comparable w){
return v.compareTo(w) < 0;
}
// 交换数组的两个元素
private static void exch(Comparable[] a, int i, int j){
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
// 测试数组是否有序
public static boolean isSorted(Comparable[] a){
for(int i = 1; i < a.length; i++){
if(less(a[i], a[i - 1])){
return false;
}
}
return true;
}
}
public class Insertion{
public static void sort(Comparable[] a){
int N = a.length;
for(int i = 1; i < N; i++){
// 将 a[i] 插入到 a[i-1], a[i-2], a[i-3]... 之中
for(int j = i; j > 0 && less(a[j], a[j - 1]); j--){
exch(a, j, j-1);
}
}
}
}
public class Shell(){
public static void sort(Comparable[] a){
int N = a.length;
int h = 1;
while(h < N/3){
h = 3 * h + 1;
}
while(h >= 1){
// 将数组变为h有序
for(int i = h; i < N; i++){
for(int j = i; j >= h && less(a[j], a[j - h]); j -= h){
exch(a, j, j-h);
}
}
h = h/3;
}
}
}
参考资料:
原文:https://www.cnblogs.com/linkworld/p/9535845.html