-
Notifications
You must be signed in to change notification settings - Fork 278
Expand file tree
/
Copy pathShellSortAditya.java
More file actions
42 lines (35 loc) · 978 Bytes
/
ShellSortAditya.java
File metadata and controls
42 lines (35 loc) · 978 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <vector>
using namespace std;
// Function to perform Shell Sort
void shellSort(vector<int> &arr) {
int n = arr.size();
// Start with a large 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];
int j;
// Shift earlier gap-sorted elements until the correct location is found
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {
arr[j] = arr[j - gap];
}
arr[j] = temp;
}
}
}
int main() {
int n;
cout << "Enter number of elements: ";
cin >> n;
vector<int> arr(n);
cout << "Enter elements: ";
for (int i = 0; i < n; i++)
cin >> arr[i];
shellSort(arr);
cout << "Sorted array: ";
for (int x : arr)
cout << x << " ";
cout << endl;
return 0;
}