📜  ShellSort的C ++程序(1)

📅  最后修改于: 2023-12-03 15:05:12.344000             🧑  作者: Mango

Shell Sort in C++

Shell Sort is an efficient sorting algorithm that is based on Insertion Sort. It is also known as diminishing increment sort, because it sorts the elements by comparing those which are far apart in the array. The algorithm starts by sorting the array with a smaller increment that is gradually increased until the entire array is sorted.

Algorithm

The algorithm works by dividing the input unsorted array into smaller subarrays, each of which is then sorted using insertion sort. The subarrays are created by considering elements that are a certain gap apart, and then comparing and swapping them if necessary. The gap value is then decreased, and the process is repeated until the gap is 1, and the entire array is sorted.

Pseudo Code
1. Start with gap = n/2 where n is the size of an array.
2. Divide the list into gap sublists of size n/gap
3. Sort each sublist using Insertion Sort.
4. Repeat step 2 and 3 with gap = gap/2 till gap = 1
Implementation
void shellSort(int arr[], int n) {
    for (int gap = n/2; gap > 0; gap /= 2) {
        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;
        }
    }
}
Complexity

The time complexity of the shell sort algorithm is O(n^2) in the worst case. However, in practice, it is much faster than the insertion sort algorithm because the elements are being compared using larger gaps initially, and smaller gaps later on. The space complexity of the algorithm is O(1), since it uses only a constant amount of extra memory to store the gap value and swap variables.

Example
int main() {
    int arr[] = {64, 25, 12, 22, 11};
    int n = sizeof(arr)/sizeof(arr[0]);
    shellSort(arr, n);
    for (int i=0; i<n; i++)
        cout << arr[i] << " ";
    return 0;
}

Output:

11 12 22 25 64
Conclusion

Shell sort is an efficient algorithm for sorting large arrays, particularly when used in conjunction with Insertion Sort. It works by comparing elements that are far apart in the array and gradually decreasing the gap, until the entire array is sorted. The time complexity of the algorithm is O(n^2), but in practice, it is much faster than Insertion Sort due to its decreased number of comparisons.