input: an array a of length n with array elements numbered 0 to n − 1 inc ← floor(n/2) while inc > 0 do: for i = inc .. n − 1 do: temp ← a[i] j ← i while j ≥ inc and a[j − inc] > temp do: a[j] ← a[j − inc] j ← j − inc a[j] ← temp inc ← floor(inc / 2)
voidshell_sort(int arr[], int len) { int gap, i, j; int temp; for (gap = len >> 1; gap > 0; gap >>= 1) for (i = gap; i < len; i++) { temp = arr[i]; for (j = i - gap; j >= 0 && arr[j] > temp; j -= gap) arr[j + gap] = arr[j]; arr[j + gap] = temp; } }
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
template<typename T> voidshell_sort(T array[], int length){ int h = 1; while (h < length / 3) { h = 3 * h + 1; } while (h >= 1) { for (int i = h; i < length; i++) { for (int j = i; j >= h && array[j] < array[j - h]; j -= h) { std::swap(array[j], array[j - h]); } } h = h / 3; } }
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
publicstaticvoidshellSort(int[] arr) { intlength= arr.length; int temp; for (intstep= length / 2; step >= 1; step /= 2) { for (inti= step; i < length; i++) { temp = arr[i]; intj= i - step; while (j >= 0 && arr[j] > temp) { arr[j + step] = arr[j]; j -= step; } arr[j + step] = temp; } } }
publicvoidshellSort(int[]a) { int h = a.Length / 2; while(h>=1) { for(int i=0;i<h;i++) { for(int j=i+h;j<a.Length;j+=h) { int temp=a[j]; int loc = j; while (loc - h >= i&&temp < a[loc - h]) { a[loc] = a[loc - h]; loc = loc - h; } a[loc] = temp; } } h = h / 2; } }
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12
functionshell_sort(arr) { for (let gap = arr.length >> 1; gap > 0; gap >>= 1) { for (let i = gap; i < arr.length; i++) { let temp = arr[i],j; for (j = i - gap; j >= 0 && arr[j] > temp; j -= gap) { arr[j + gap] = arr[j]; } arr[j + gap] = temp; } } return arr; };
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
defshell_sort(list): n = len(list) # 初始步長 gap = n // 2 while gap > 0: for i inrange(gap, n): # 每个步長進行插入排序 temp = list[i] j = i # 插入排序 while j >= 0and j-gap >= 0andlist[j - gap] > temp: list[j] = list[j - gap] j -= gap list[j] = temp # 得到新的步長 gap = gap // 2 returnlist