Skip to content

Commit aa95f46

Browse files
authored
Merge pull request #722 from iamsid2/master
coctail sort using cpp
2 parents e831ddd + 60e5c61 commit aa95f46

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

sorting/Cocktail_Sort

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// C++ implementation of Cocktail Sort
2+
#include<bits/stdc++.h>
3+
using namespace std;
4+
5+
void CocktailSort(int a[], int n)
6+
{
7+
bool swapped = true;
8+
int start = 0;
9+
int end = n-1;
10+
11+
while (swapped)
12+
{
13+
14+
swapped = false;
15+
16+
for (int i = start; i < end; ++i)
17+
{
18+
if (a[i] > a[i + 1])
19+
{
20+
swap(a[i], a[i+1]);
21+
swapped = true;
22+
}
23+
}
24+
25+
if (!swapped)
26+
break;
27+
swapped = false;
28+
29+
30+
--end;
31+
32+
for (int i = end - 1; i >= start; --i)
33+
{
34+
if (a[i] > a[i + 1])
35+
{
36+
swap(a[i], a[i+1]);
37+
swapped = true;
38+
}
39+
}
40+
41+
// increase the starting point, because
42+
// the last stage would have moved the next
43+
// smallest number to its rightful spot.
44+
++start;
45+
}
46+
}
47+
48+
void printArray(int a[], int n)
49+
{
50+
for (int i=0; i<n; i++)
51+
printf("%d ", a[i]);
52+
printf("\n");
53+
}
54+
55+
int main()
56+
{
57+
int arr[] = {5, 1, 4, 2, 8, 0, 2};
58+
int n = sizeof(arr)/ sizeof(arr[0]);
59+
CocktailSort(a,n);
60+
printf("Sorted array :\n");
61+
printArray(a,n);
62+
return 0;
63+
}

0 commit comments

Comments
 (0)