Shell Sort in C++

Below is an example of the Shellsort algorithm in C++. See the Shellsort page for more information and implementations.


shellsort in C++

#include <iostream>
#include <vector>

void shellSort(std::vector<int> &arr) {
    /*
     * for-loop setup:
     *      1. set the gapSize to the size of the array / 2
     *      2. run the loop as long as gapSize > 0
     */
    for (int gapSize = arr.size() / 2; gapSize > 0; gapSize /= 2) {
        for (int currentIndex = gapSize; currentIndex < arr.size(); currentIndex++) {
            // save the currentIndex
            int currentIndexCopy = currentIndex;
            // save the value of the currentIndex
            int item = arr[currentIndex];

            while (currentIndexCopy >= gapSize && arr[currentIndexCopy - gapSize] > item) {
                arr[currentIndexCopy] = arr[currentIndexCopy - gapSize];
                currentIndexCopy -= gapSize;
            }

            arr[currentIndexCopy] = item;
        }
    }
}

int main() {
    std::vector<int> arr = {12, 11, 15, 10, 9, 1, 2, 3, 13, 14, 4, 5, 6, 7, 8};
    shellSort(arr);
    for (int i; i < arr.size(); i++) {
        std::cout << arr[i];
        if (i < arr.size() - 1) std::cout << ", ";
    }
}

Discussion