Shellsort : Sort « Collections « Java Tutorial






public class MainClass {
  public static void main(String[] args) {
    int[] intArray = { 1, 9, 2, 8, 3, 7, 4, 6, 5 };

    for (int i : intArray) {
      System.out.println(i);
    }

    shellSort(intArray);
    System.out.println("after: ");
    for (int i : intArray) {
      System.out.println(i);
    }
  }

  public static void shellSort(int[] intArray) {
    int inner, outer;
    int temp;

    int h = 1;
    while (h <= intArray.length / 3){
      h = h * 3 + 1;
    }
    while (h > 0) {
      for (outer = h; outer < intArray.length; outer++) {
        temp = intArray[outer];
        inner = outer;

        while (inner > h - 1 && intArray[inner - h] >= temp) {
          intArray[inner] = intArray[inner - h];
          inner -= h;
        }
        intArray[inner] = temp;
      }
      h = (h - 1) / 3;
    }
  }
}
1
9
2
8
3
7
4
6
5
after: 
1
2
3
4
5
6
7
8
9








9.53.Sort
9.53.1.Bubble Sort
9.53.2.Selection Sort
9.53.3.Insertion Sort
9.53.4.Sorting Objects using insertion sort
9.53.5.Mergesort: merging two arrays into a third
9.53.6.Generic Merge Sorter with generic Comparator
9.53.7.Shellsort
9.53.8.Quicksort: simple version of quick sort
9.53.9.Quick sort with median-of-three partitioning
9.53.10.Quick sort: uses an insertion sort to handle subarrays of fewer than 10 cells