-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshellsort.cpp
More file actions
79 lines (66 loc) · 1.6 KB
/
shellsort.cpp
File metadata and controls
79 lines (66 loc) · 1.6 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
#include <iostream>
using namespace std;
void shellSort(int arr[], int n)
{
int comp=0,swaps=0;
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];
comp++;
}
swaps++;
arr[j] = temp;
}
}
cout<<"In shell sort,"<<endl<<" No. of comparisons: "<<comp<<endl<<"No. of swaps: "<<swaps<<endl;
}
void insertionSort(int arr[], int n)
{
int i, key, j;
int comp=0,swap=0;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
comp++;
}
arr[j + 1] = key;
swap++;
}
cout<<"In shell sort,"<<endl<<" No. of comparisons: "<<comp<<endl<<"No. of swaps: "<<swap<<endl;
}
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
int main()
{
int size;
cout<<"Enter the size of the array: "<<endl;
cin>>size;
int arr1[size];
cout<<"Enter the array elements: "<<endl;
for(int i=0;i<size;i++)
cin>>arr1[i];
int arr2[size];
for(int i=0;i<size;i++)
arr2[i]=arr1[i];
cout << "Array before sorting: \n";
printArray(arr1, size);
shellSort(arr1, size);
insertionSort(arr2,size);
cout << " Array after sorting using Shell Sort: "<<endl;
printArray(arr1, size);
return 0;
}