[关闭]
@XQF 2018-03-07T22:55:00.000000Z 字数 512 阅读 780

排序----希尔排序

数据结构与算法


主要是这个按照某种间隔进行分组,以插入排序为基础。

gap为1的时候的就等同于插入排序

  1. public class Solution {
  2. public int[] shellSort(int[] nums) {
  3. int len = nums.length;
  4. //gap是不能为0的,注意
  5. for (int gap = len / 2; gap > 0; gap /= 2) {
  6. // 对所有元素插入排序,间隔为gap
  7. for (int i = gap; i < len; i++) {
  8. int temp = nums[i];
  9. int j;
  10. for (j = i - gap; j >= 0; j -= gap) {
  11. if (temp < nums[j]) {
  12. nums[j + gap] = nums[j];
  13. } else {
  14. break;
  15. }
  16. }
  17. nums[gap + j] = temp;
  18. }
  19. }
  20. return nums;
  21. }
  22. public static void main(String[] args) {
  23. int[] nums = {1, 2, 55, 6, 3, 2, 4, 5, 6, 8, 9, 0};
  24. Solution solution = new Solution();
  25. System.out.println(Arrays.toString(solution.shellSort(nums)));
  26. }
  27. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注