Skip to content

Commit 8e7d149

Browse files
authored
Merge pull request larissalages#172 from saiharsha-22/master
Added Sorting algorithms in C++
2 parents 4f50527 + ba276ce commit 8e7d149

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

classical_algorithms/c++/SHELLSOR.CPP

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
2+
// Shell sort algorithm time complexity is best case O(nlogn) and worst case O(n^2)
3+
4+
#include<iostream>
5+
using namespace std;
6+
class shellsort
7+
{
8+
private:
9+
int a[20], n, i, j, gap, temp;
10+
public:
11+
void getdata ()
12+
{
13+
cout << "enter number of elemnts:\n";
14+
cin >> n;
15+
cout << "enter the elements:\n";
16+
for (i = 0; i < n; i++)
17+
{
18+
cin >> a[i];
19+
}
20+
}
21+
void shellsorting ()
22+
{
23+
24+
for (gap = n / 2; gap > 0; gap = gap / 2)
25+
{
26+
for (j = gap; j < n; j++)
27+
{
28+
for (i = j - gap; i >= 0; i -= gap)
29+
{
30+
if (a[i + gap] > a[i])
31+
{
32+
break;
33+
}
34+
else
35+
{
36+
swap ();
37+
}
38+
}
39+
}
40+
}
41+
}
42+
void swap ()
43+
{
44+
temp = a[i + gap];
45+
a[i + gap] = a[i];
46+
a[i] = temp;
47+
48+
}
49+
void display ()
50+
{
51+
for (i = 0; i < n; i++)
52+
{
53+
cout << a[i] << "\t";
54+
}
55+
}
56+
};
57+
58+
int main ()
59+
{
60+
61+
shellsort obj;
62+
obj.getdata ();
63+
cout << "before sorting:";
64+
obj.display ();
65+
obj.shellsorting ();
66+
cout << endl << "after sorting:";
67+
obj.display ();
68+
return 0;
69+
}

0 commit comments

Comments
 (0)