shell sort

 avatar
user_9350232
plain_text
9 months ago
803 B
13
Indexable
#include <iostream>
using namespace std;

void shellSort(int arr[], int n) {
    for (int gap = n / 2; gap > 0; gap /= 2) {
        for (int i = gap; i < n; i++) {
            int temp = arr[i];
            int j = i;
            while (j >= gap && arr[j - gap] > temp) {
                arr[j] = arr[j - gap];
                j -= gap;
            }
            arr[j] = temp;
        }
    }
}

int main() {
    int arr[] = {12, 34, 54, 2, 3};
    int n = 5;

    cout << "Original array: ";
    for (int i = 0; i < n; i++) cout << arr[i] << " ";

    shellSort(arr, n);

    cout << "\nSorted array (Shell Sort): ";
    for (int i = 0; i < n; i++) cout << arr[i] << " ";

    cout << "\n\nTime Complexity: O(n^(3/2)) approx\nSpace Complexity: O(1)\n";
    return 0;
}
Editor is loading...
Leave a Comment