java常见排序算法——希尔排序(附代码示列)

2025年01月13日 建站教程

希尔-冒泡排序(慢)

public void shellBubbleSort(int[] nums){
  for (int step = nums.length/2; step > 0 ; step /= 2) {
    for (int i = step; i < nums.length; i++) {
      for (int j = i-step; j >= 0; j -= step) {
        if(nums[j] > nums[j+step]){
          int temp = nums[j];
          nums[j] = nums[j+step];
          nums[j+step] = temp;
        }
      }
    }
  }
}

希尔-插入排序(快)

public void shellInsertSort(int[] nums){
  for (int step = nums.length/2; step > 0; step /= 2) {
    for (int i = step; i < nums.length; i++) {
      int j = i;
      int insertNum = nums[i];
      while(j-step >= 0 && nums[j-step] > insertNum){
        nums[j] = nums[j-step];
        j-=step;
      }
      nums[j] = insertNum;
    }
  }
}

PS:引入步长减少数字交换次数提高效率

本文链接:http://so.lmcjl.com/news/21263/

展开阅读全文
相关内容