Name: Tanishq Tyagi
Roll No.:2300320100262
Shell Sort
Theory:
Shell Sort is an improved version of Insertion Sort.
It works by comparing and sorting elements that are far apart, then gradually reducing the gap
between elements being compared.
This helps move elements closer to their correct positions faster than simple insertion sort.
Code:
#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;
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {
arr[j] = arr[j - gap];
}
arr[j] = temp;
}
}
}
int main() {
int arr[] = {23, 12, 1, 8, 34, 54, 2, 3};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Before sort: ";
for (int i = 0; i < n; i++) cout << arr[i] << " ";
cout << endl;
shellSort(arr, n);
cout << "After sort: ";
for (int i = 0; i < n; i++) cout << arr[i] << " ";
cout << endl;
return 0;
}
Output: