File tree 1 file changed +63
-0
lines changed 1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change
1
+ // C++ implementation of Shell Sort
2
+ #include < iostream>
3
+ using namespace std ;
4
+
5
+ // Function to sort array using shellSort
6
+ int shellSort (int arr[], int n)
7
+ {
8
+ // Start with a big gap, then reduce the gap
9
+ for (int gap = n/2 ; gap > 0 ; gap /= 2 )
10
+ {
11
+ /* Do a gapped insertion sort for this gap size.
12
+ The first gap elements a[0..gap-1] are already in gapped order
13
+ keep adding one more element until the entire array is
14
+ gap sorted */
15
+ for (int i = gap; i < n; i += 1 )
16
+ {
17
+ /* add a[i] to the elements that have been gap sorted
18
+ save a[i] in temp and make a hole at position i */
19
+ int temp = arr[i];
20
+
21
+ /* shift earlier gap-sorted elements up until the correct
22
+ location for a[i] is found*/
23
+ int j;
24
+ for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
25
+ arr[j] = arr[j - gap];
26
+
27
+ // put temp (the original a[i]) in its correct location
28
+ arr[j] = temp;
29
+ }
30
+ }
31
+ return 0 ;
32
+ }
33
+
34
+ void printArray (int arr[], int n)
35
+ {
36
+ for (int i=0 ; i<n; i++)
37
+ cout << arr[i] << " " ;
38
+ cout<<endl;
39
+ }
40
+
41
+ int main ()
42
+ {
43
+ int n;
44
+ cout<<" Enter number of elements in array\n " ;
45
+ cin>>n;
46
+
47
+ int arr[n], i;
48
+ cout<<" Enter elements of array\n " ;
49
+ for (i=0 ;i<n;i++)
50
+ {
51
+ cin>>arr[i];
52
+ }
53
+
54
+ cout << " Array before sorting: \n " ;
55
+ printArray (arr, n);
56
+
57
+ shellSort (arr, n);
58
+
59
+ cout << " Array after sorting: \n " ;
60
+ printArray (arr, n);
61
+
62
+ return 0 ;
63
+ }
You can’t perform that action at this time.
0 commit comments