package org.structure.sort;
import java.util.Arrays;
/**
* 希尔排序
* @author cjj_1
* @date 2020-08-13 14:17
*/
public class ShellSort {
public static void main(String[] args) {
int[] arr = {8,9,1,7,2,3,5,4,6,0};
shellSort1(arr);
print(arr);
}
/**
*
* @param arr
*/
public static void shellSort(int[] arr){
int temp;
for(int gap = arr.length/2;gap>0;gap = gap/2){//分组
for(int i = gap;i<arr.length;i++){//给每个元素排序
for(int j = i-gap;j>=0;j-=gap){//组内成员交换排序
if(arr[j+gap]<arr[j]){
temp = arr[j];
arr[j] = arr[j+gap];
arr[j+gap] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
}
}
/**
* 交换法,效率高
* @param arr
*/
public static void shellSort1(int[] arr) {
int temp;
int index;
for (int gap = arr.length / 2; gap > 0; gap = gap / 2) {//分组
for (int i = gap; i < arr.length; i++) {//给每个元素排序
index = i;
temp = arr[index];
while (index>=gap && arr[index]<arr[index-gap]){
arr[index] = arr[index-gap];
index -= gap;
}
arr[index] = temp;
}
System.out.println(Arrays.toString(arr));
}
}
public static void print(int[] arr){
for (int i =0;i<arr.length;i++){
System.out.printf("%d\t",arr[i]);
}
}
}
希尔排序
最新推荐文章于 2024-06-04 00:42:18 发布