Shell Sort Algorithm in CPP

1. Introduction

Shell Sort, also known as the diminishing increment sort, is a generalization of the insertion sort. Instead of comparing adjacent elements, Shell Sort compares elements that are a specific interval apart, where this interval reduces with each pass. The interval starts with a larger value and progressively reduces to 1, ensuring the list is sorted at the end.

2. Implementation Steps

1. Choose a gap sequence. A common choice is to start with n/2 and reduce the gap by half in each iteration, where n is the length of the array.

2. Perform insertion sort for each gap.

3. Decrease the gap and repeat the process until the gap is 1.

3. Implementation in C++ Programming

#include<iostream>
#include<vector>
void shellSort(std::vector<int>& arr) {
    int n = arr.size();
    // Start with a big gap, then reduce the gap
    for (int gap = n / 2; gap > 0; gap /= 2) {
        // Do a gapped insertion sort for this gap size
        for (int i = gap; i < n; i += 1) {
            int temp = arr[i];
            int j;
            for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
                arr[j] = arr[j - gap];
            arr[j] = temp;
        }
    }
}
int main() {
    std::vector<int> arr = {12, 34, 54, 2, 3};
    shellSort(arr);
    std::cout << "Sorted array: \n";
    for (int i = 0; i < arr.size(); i++) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;
    return 0;
}

Output:

Sorted array:
2 3 12 34 54

Explanation:

1. Shell Sort begins by sorting pairs of elements that are far apart (based on the chosen gap sequence) and gradually reduces the gap, leading to more elements being compared and swapped.

2. With each pass and a smaller gap, the array becomes more sorted. By the time the gap is 1, a regular insertion sort is performed. However, due to previous passes, most elements are already in their correct places, making this final insertion sort fast.

3. The choice of gap sequence can influence the performance. The example above uses the simplest gap sequence (reducing the gap by half in each iteration), but other sequences like the Pratt sequence or the Ciura sequence can offer better performance.


Comments