希尔排序:是对直接插入排序的优化
public static void main(String[] args) {
int[] array = {-1, 9, 7, 6, 100, 60, 35};
shellSortDesc(array);
shellSortAsc(array);
}
/**
* 希尔排序 降序
*
* @param array
*/
public static void shellSortDesc(int[] array) {
for (int gap = array.length / 2; gap > 0; gap /= 2) {
for (int i = gap; i < array.length; i++) {
int insertIndex = i;
int insertValue = array[insertIndex];
while (insertIndex - gap >= 0 && insertValue > array[insertIndex - gap]) {
array[insertIndex] = array[insertIndex - gap];
insertIndex -= gap;
}
array[insertIndex] = insertValue;
}
}
System.out.println(Arrays.toString(array));
}
/**
* 希尔排序 :升序
* @param array
*/
public static void shellSortAsc(int[] array) {
for (int gap = array.length / 2; gap > 0; gap /= 2) {
for (int i = gap; i < array.length; i++) {
int insertIndex = i;
int insertValue = array[insertIndex];
while (insertIndex - gap >= 0 && insertValue < array[insertIndex - gap]) {
array[insertIndex] = array[insertIndex - gap];
insertIndex -= gap;
}
array[insertIndex] = insertValue;
}
}
System.out.println(Arrays.toString(array));
}
}