1. 程式人生 > >希爾排序演算法(java版)

希爾排序演算法(java版)

  • 希爾排序:直接插入排序的改良版,威力更強。
  • 直接插入排序是每一移一個,比較相鄰的兩個
  • 希爾排序第一次分堆是 n = n / 2為一堆的,也就是下標為i的元素和下標為i + n/2,i + n/2 +… < n的元素作為一堆的,
  • 每次比較i 和 i + n /2 的元素,保證n[i] < n[i + n/2]
  • 第二次分堆 step = n / 4,每次加step詞,保證 i + step + …的次序

java程式碼:

package com.zhangyike.shellSort;

import java.util.Arrays;
import java.util.Random;

public
class ShellSort { public static void main(String args[]) { int count = 10; int n[] = new int[count]; Random rd = new Random(); for (int i = 0; i < n.length; i++) { n[i] = rd.nextInt(count); } System.out.println("排序前:" + Arrays.toString(n)); shellSort(n,n.length); System.out
.println("排序後:" + Arrays.toString(n)); } public static void shellSort(int[] n, int len){ int step = 0; //選擇步長 for (step = len/2; step > 0; step /= 2) { //對改步長內的分組進行排序 for (int i = step; i < len; i++) { int tmp = n[i]; int
position = i; //對改步長內的元素進行插入 while(position >= step && tmp < n[position - step]){ n[position] = n[position - step]; position -= step; } n[position] = tmp; } } } }