Shell排序Java实现
排序父类
-
排序模板用于继承
Sort.java
package MYSORT;
public class Sort {
public static void sort(Comparable[] a, boolean printProcess)
{}
public static boolean less(Comparable v, Comparable w)
{ return v.compareTo(w) < 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 print(Comparable[] a)
{
String status = "Disordered";
if (isSorted(a)) status="Ordered";
for (int i = 0; i<a.length; i++)
System.out.print(a[i]+"| ");
System.out.print(status);
System.out.println();
}
public static boolean isSorted(Comparable[] a)
{
for (int i = 0; i<a.length-1; i++)
if (less(a[i+1], a[i]))
return false;
return true;
}
}
元素类型
-
实现了Comparable接口
-
用作排序的元素
intForSort.java
package MYSORT;
public class intForSort implements Comparable<intForSort> {
private int data;
public intForSort(int data)
{this.data = data;}
@Override
public int compareTo(intForSort o) {
if (this.data>o.data) return 1;
if (this.data==o.data) return 0;
return -1;
}
@Override
public String toString() {
return String.valueOf(data);
}
}
Shell排序
ShellSort.java
package MYSORT;
public class ShellSort extends Sort {
public static void sort(Comparable[] a, boolean printProcess)
{
int h = 1;
while (h<a.length/3) h = 3*h+1;
while (h>=1)
{
for (int i=h; i<a.length; i++)
{
for (int j=i; j>=h&&less(a[j], a[j-h]); j-=h)
exchange(a,j,j-h);
}
h = h/3;
if (printProcess) print(a);
}
}
}
排序测试
SortTest.java
package MYSORT;
public class SortTest {
public static void main(String[] args) {
int[] data = {5,5,9,6,7,9,1,12,35,62,14,181,17,2,23,88,45,76,98,145,126,26,45,18,13,24};
intForSort []elems = new intForSort[data.length];
for (int i = 0;i<data.length;i++)
{
elems[i] = new intForSort(data[i]);
}
System.out.println("排序前:");
Sort.print(elems);
System.out.println("Shell排序过程:");
ShellSort.sort(elems,true);
System.out.println("排序后:");
Sort.print(elems);
}
}
运行结果
排序前:
5| 5| 9| 6| 7| 9| 1| 12| 35| 62| 14| 181| 17| 2| 23| 88| 45| 76| 98| 145| 126| 26| 45| 18| 13| 24| Disordered
Shell排序过程:
2| 5| 9| 6| 7| 9| 1| 12| 26| 45| 14| 13| 17| 5| 23| 88| 45| 76| 98| 145| 126| 35| 62| 18| 181| 24| Disordered
2| 5| 1| 6| 7| 5| 9| 12| 17| 9| 14| 13| 26| 24| 23| 18| 45| 35| 62| 88| 126| 45| 98| 145| 181| 76| Disordered
1| 2| 5| 5| 6| 7| 9| 9| 12| 13| 14| 17| 18| 23| 24| 26| 35| 45| 45| 62| 76| 88| 98| 126| 145| 181| Ordered
排序后:
1| 2| 5| 5| 6| 7| 9| 9| 12| 13| 14| 17| 18| 23| 24| 26| 35| 45| 45| 62| 76| 88| 98| 126| 145| 181| Ordered
参考资料
Robert Sedgewick and Kevin Wayne《Algorithms》FOURTH EDITION