Shell排序



package com.xj.www.sort;
/**
 * Shell排序算法
 *
 * @author xiongjing
 *
 */
public class SelectSort {
      /**
       * 选择排序具体流程实现如下:
       * 1.首先从原始数组中选择最小的1个数据,将其和位于第1个位置的数据进行交换。
       * 2.接着从剩下的n-1个数据中选择次小的1个数据,将其个第2个位置的数据进行交换。
       * 3.不断重复以上过程,直到最后两个数据完成交换。
       */
      final static int SIZE = 10;
      public static void Select(int[] a) {
            int index, temp;
            for (int i = 0; i < a.length - 1; i++) {
                  index = i;
                  for (int j = i + 1; j < a.length; j++) {
                        if (a[j] < a[index]) {
                              index = j;
                        }
                  }
                  // 交换两个数
                  if (index != i) {
                        temp = a[i];
                        a[i] = a[index];
                        a[index] = temp;
                  }
                  System.out.print("第" + i + "步排序结果:");
                  for (int h = 0; h < a.length; h++) {
                        System.out.print(" " + a[h]);
                  }
                  System.out.print("\n");
            }
      }
      // 算法主入口
      public static void main(String[] args) {
            long startTime = System.currentTimeMillis();
            int[] shuzu = new int[SIZE];
            int i;
            for (i = 0; i < SIZE; i++) {
                  shuzu[i] = (int) (100 + Math.random() * (100 + 1));
            }
            System.out.println("排序前的数组为:");
            for (i = 0; i < SIZE; i++) {
                  System.out.print(shuzu[i]+" ");
            }
            System.out.print("\n");
            Select(shuzu);
            System.out.println("排序后的数组为:");
            for (i = 0; i < SIZE; i++) {
                  System.out.print(shuzu[i]+" ");
            }
            System.out.print("\n");
            long endTime = System.currentTimeMillis();
            long totalTime = endTime - startTime;
            System.out.println("总共用时:"+totalTime);
      }
}

你可能感兴趣的:(Shell排序)