利用Java进行希尔排序(元素中有0会有问题),步长经过调试length/2+1最合适。
1 import java.util.Scanner; 2 3 public class HierSort { 4 private static int array[] = new int[100000]; 5 6 private static void setArray(int length){ 7 Scanner scanner = new Scanner(System.in); 8 System.out.println("Please entry Array elements:"); 9 for (int i = 0; i < length; i++) { 10 int num = scanner.nextInt(); 11 array[i] = num; 12 } 13 } 14 15 private static void show(int length){ 16 System.out.println("Output this array:"); 17 for (int i = 0; i < length; i++) { 18 System.out.print(array[i] + " "); 19 } 20 } 21 22 private static void Hier(int length){ 23 // define a flag as this HieSort of path 24 int flag; 25 flag = length / 2 + 1; 26 while (flag > 0){ 27 for (int i = 0; i < length; i++) { 28 // judge of edge because the length less than the length of array 29 if (array[i] > array[i+flag] && array[i+flag] != array[length]){ 30 int swap; 31 swap = array[i+flag]; 32 array[i+flag] = array[i]; 33 array[i] = swap; 34 } 35 } 36 // System.out.println(flag); 37 // sub this flag util the f lag equals one 38 flag--; 39 } 40 } 41 42 public static void main(String[] args){ 43 int length; 44 Scanner scanner = new Scanner(System.in); 45 System.out.println("Please the length of array(0<x<10000):"); 46 length = scanner.nextInt(); 47 setArray(length); 48 Hier(length); 49 show(length); 50 } 51 }