How it works
Generalizes insertion sort to allow exchanges of elements far apart. Uses a decreasing sequence of gap values.
Implementation
function shellSort(arr, stats) { const n = arr.length; let pass = 0; for (let gap = Math.floor(n / 2); gap > 0; gap = Math.floor(gap / 2)) { for (let i = gap; i < n; i++) { const temp = arr[i]; let j = i; while (j >= gap) { compare(j - gap, i); if (arr[j - gap] <= temp) break; arr[j] = arr[j - gap]; swap(j, j - gap); j -= gap; } arr[j] = temp; write(j, temp); } pass++; checkpoint(pass, Math.max(1, pass + 1)); } for (let i = 0; i < n; i++) markSorted(i); }
def shellSort(arr, stats): pass = 0 gap = (n // 2) while (gap > 0): for i in range(gap, n): temp = arr[i] j = i while (j >= gap): compare((j - gap), i) if (arr[(j - gap)] <= temp): break arr[j] = arr[(j - gap)] swap(j, (j - gap)) j -= gap arr[j] = temp write(j, temp) pass += 1 checkpoint(pass, (1 if 1 >= (pass + 1) else (pass + 1))) gap = (gap // 2) for i in range(n): markSorted(i)
#include <vector> #include <algorithm> void sort(std::vector<int>& arr, int n, int& comparisons, int& swaps) { int pass = 0; for(int gap=(n / 2); (gap > 0); gap = (gap / 2)) { for(int i=gap; i<n; i++) { int temp = arr[i]; int j = i; while((j >= gap)) { compare((j - gap), i); if((arr[(j - gap)] <= temp)) { break; } arr[j] = arr[(j - gap)]; swap(j, (j - gap)); j -= gap; } arr[j] = temp; write(j, temp); } pass++; checkpoint(pass, ((1) > ((pass + 1)) ? (1) : ((pass + 1)))); } for(int i=0; i<n; i++) { markSorted(i); } }
public void Sort(int[] arr, int n, dynamic stats) { int pass = 0; for(int gap=(n / 2); (gap > 0); gap = (gap / 2)) { for(int i=gap; i<n; i++) { int temp = arr[i]; int j = i; while((j >= gap)) { compare((j - gap), i); if((arr[(j - gap)] <= temp)) { break; } arr[j] = arr[(j - gap)]; swap(j, (j - gap)); j -= gap; } arr[j] = temp; write(j, temp); } pass++; checkpoint(pass, Math.Max(1, (pass + 1))); } for(int i=0; i<n; i++) { markSorted(i); } }
#include <stdio.h> void sort(int arr[], int n, int* comparisons, int* swaps) { int pass = 0; for(int gap=(n / 2); (gap > 0); gap = (gap / 2)) { for(int i=gap; i<n; i++) { int temp = arr[i]; int j = i; while((j >= gap)) { compare((j - gap), i); if((arr[(j - gap)] <= temp)) { break; } arr[j] = arr[(j - gap)]; swap(j, (j - gap)); j -= gap; } arr[j] = temp; write(j, temp); } pass++; checkpoint(pass, ((1) > ((pass + 1)) ? (1) : ((pass + 1)))); } for(int i=0; i<n; i++) { markSorted(i); } }