利用Java进行希尔排序(元素中有0会有问题),步长经过调试length/2+1最合适。
import java.util.Scanner; public class HierSort {
private static int array[] = new int[100000]; private static void setArray(int length){
Scanner scanner = new Scanner(System.in);
System.out.println("Please entry Array elements:");
for (int i = 0; i < length; i++) {
int num = scanner.nextInt();
array[i] = num;
}
} private static void show(int length){
System.out.println("Output this array:");
for (int i = 0; i < length; i++) {
System.out.print(array[i] + " ");
}
} private static void Hier(int length){
// define a flag as this HieSort of path
int flag;
flag = length / 2 + 1;
while (flag > 0){
for (int i = 0; i < length; i++) {
// judge of edge because the length less than the length of array
if (array[i] > array[i+flag] && array[i+flag] != array[length]){
int swap;
swap = array[i+flag];
array[i+flag] = array[i];
array[i] = swap;
}
}
// System.out.println(flag);
// sub this flag util the f lag equals one
flag--;
}
} public static void main(String[] args){
int length;
Scanner scanner = new Scanner(System.in);
System.out.println("Please the length of array(0<x<10000):");
length = scanner.nextInt();
setArray(length);
Hier(length);
show(length);
}
}