Description: Shell sort is an optimization of insertion sort that allows the exchange of items that are far apart. It uses a gap sequence to determine which elements to compare and swap. The idea is to allow the elements to move more quickly to their correct positions, effectively reducing the overall sorting time.
Here's a C++ implementation of shell sort:
#include <iostream>
using namespace std;
void shellSort(int arr[], int n) {
// 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++) {
int temp = arr[i]; // Element to be positioned
int j;
// Shift earlier gap-sorted elements up until the correct location for arr[i] is found
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {
arr[j] = arr[j - gap];
}
arr[j] = temp; // Put temp (the original arr[i]) in its correct location
}
}
}
int main() {
int arr[] = {12, 34, 54, 2, 3};
int n = sizeof(arr) / sizeof(arr[0]);
shellSort(arr, n);
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
shellSort function takes an array and its size as parameters.gap distance apart.temp) to be placed in its correct position.Shell sort improves upon insertion sort by allowing the exchange of distant elements, thus reducing the number of comparisons and movements needed as the gaps decrease. While not as efficient as more advanced algorithms like quick sort or merge sort for large datasets, it is simple to implement and can be very effective for smaller lists. Its in-place nature and lower overhead make it a useful choice for certain applications where memory usage is a concern.
Open this section to load past papers