. Shell sort in c++
Here is a response for the Shell sort in C++ with explanations for each step:
#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 += 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;
}
}
}
int main() {
int arr[] = {12, 34, 54, 2, 3};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Array before sorting: \n";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
shellSort(arr, n);
cout << "\nArray after sorting: \n";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
Explanation: - The shellSort function takes an array and its size as input parameters. - It initializes the gap as n/2 and iterates until the gap is greater than 0, reducing the gap by half in each iteration. - Inside the outer loop, it performs insertion sort for each sub-array with a specific gap. - The main function initializes an array and its size, then prints the array before sorting. - It calls the shellSort function to sort the array and then prints the array after sorting.