-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathshellsort.cpp
More file actions
84 lines (61 loc) · 1.79 KB
/
shellsort.cpp
File metadata and controls
84 lines (61 loc) · 1.79 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Shell Sort
// Shellsort, also known as Shell's method, is an in-place comparison sort. It can be seen as either a generalization of sorting by exchange or sorting by insertion. The method starts by sorting pairs of elements far apart from each other, then progressively reducing the gap between elements to be compared.
// Algorithm
// ShellSort(array, size)
// for interval i <- size/2n down to 1
// for each interval "i" in array
// sort all the elements at interval "i"
// end shellSort
// Shell Sort in C++ programming
#include <iostream>
using namespace std;
// Shell sort
void shellSort(int arr[], int n)
{
// Rearrange elements at each n/2, n/4, n/8, ... intervals
for (int interval = n / 2; interval > 0; interval /= 2)
{
for (int i = interval; i < n; i += 1)
{
int temp = arr[i];
int j;
for (j = i; j >= interval && arr[j - interval] > temp; j -= interval)
{
arr[j] = arr[j - interval];
}
arr[j] = temp;
}
}
}
// Print an array
void print(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
// Driver code
int main()
{
int arr[] = {9, 8, 3, 7, 5, 6, 4, 1};
int n = sizeof(arr) / sizeof(arr[0]);
shellSort(arr, n);
cout << "Sorted array: \n";
print(arr, n);
}
// Output
// Array before sorting:
// 9 8 3 7 5 6 4 1
// Array after sorting:
// 1 3 4 5 6 7 8 9
// Time Complexity:
// Best - O(nlog n)
// Worst - O(n2)
// Average - O(nlog n)
// Space Complexity:
// O(1)
// Stability:
// Not a stable algorithm.
// Stability of a sorting algorithm means that- when two instances with equal values appear in the same order in the sorted output as they appear in the array as given by the user.