希尔排序
package demo;
public class ShellSort {
public static void main(String[] args) {
int[] arr = {5,4,3,2,1,0};
printArr(arr);
shellSort(arr);
printArr(arr);
}
private static void shellSort(int[] arr) {
int gap = arr.length / 2;
while (gap > 0) {
for (int i = gap; i < arr.length; i++) {
int tmp = arr[i];
int j = i - gap;
for (; j >= 0 && arr[j] > tmp; j = j - gap) {
arr[j+gap]=arr[j];
}
arr[j+gap] = tmp;
}
gap = gap/2;
}
}
/**
* 打印数组;
*
* @param arr
*/
private static void printArr(int[] arr) {
if (arr == null) {
return;
}
for (int i = 0; i < arr.length; i++) {
if (i != arr.length - 1) {
System.out.print(arr[i] + " ");
} else {
System.out.print(arr[i]);
}
}
System.out.println();
}
}
多思考,多尝试。