Skip to content

Commit c098b4c

Browse files
Create ShellSortAditya.java
Shell Sort is an optimized version of Insertion Sort that allows the exchange of far-apart elements. The array is sorted using gaps that reduce by half each iteration. When the gap becomes 1, it effectively becomes a normal insertion sort — but the array is mostly sorted by then. Complexity: Best case: O(n log n) Average case: O(n^(3/2)) Worst case: O(n²) Space complexity: O(1)
1 parent 09c5814 commit c098b4c

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include <iostream>
2+
#include <vector>
3+
using namespace std;
4+
5+
// Function to perform Shell Sort
6+
void shellSort(vector<int> &arr) {
7+
int n = arr.size();
8+
9+
// Start with a large gap, then reduce the gap
10+
for (int gap = n / 2; gap > 0; gap /= 2) {
11+
// Do a gapped insertion sort for this gap size
12+
for (int i = gap; i < n; i++) {
13+
int temp = arr[i];
14+
int j;
15+
// Shift earlier gap-sorted elements until the correct location is found
16+
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {
17+
arr[j] = arr[j - gap];
18+
}
19+
arr[j] = temp;
20+
}
21+
}
22+
}
23+
24+
int main() {
25+
int n;
26+
cout << "Enter number of elements: ";
27+
cin >> n;
28+
29+
vector<int> arr(n);
30+
cout << "Enter elements: ";
31+
for (int i = 0; i < n; i++)
32+
cin >> arr[i];
33+
34+
shellSort(arr);
35+
36+
cout << "Sorted array: ";
37+
for (int x : arr)
38+
cout << x << " ";
39+
cout << endl;
40+
41+
return 0;
42+
}

0 commit comments

Comments
 (0)