0% found this document useful (0 votes)
5 views1 page

Shell Sort Algorithm Explained

Shell Sort is an enhanced version of Insertion Sort that sorts elements by comparing those that are far apart and gradually reducing the gap. The provided code implements Shell Sort in C++, demonstrating its functionality with an example array. The output shows the array before and after sorting.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views1 page

Shell Sort Algorithm Explained

Shell Sort is an enhanced version of Insertion Sort that sorts elements by comparing those that are far apart and gradually reducing the gap. The provided code implements Shell Sort in C++, demonstrating its functionality with an example array. The output shows the array before and after sorting.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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:

You might also like