Skip to content

Commit d3c6089

Browse files
authored
Merge pull request #103 from bilgehanmb/patch-1
Create CocktailSort.cpp
2 parents 6ebcfb8 + 90e113b commit d3c6089

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

C++/CocktailSort.cpp

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
// Sorts arrar a[0..n-1] using Cocktail sort
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+
// reset the swapped flag on entering
13+
// the loop, because it might be true from
14+
// a previous iteration.
15+
swapped = false;
16+
17+
// loop from left to right same as
18+
// the bubble sort
19+
for (int i = start; i < end; ++i) {
20+
if (a[i] > a[i + 1]) {
21+
swap(a[i], a[i + 1]);
22+
swapped = true;
23+
}
24+
}
25+
26+
// if nothing moved, then array is sorted.
27+
if (!swapped)
28+
break;
29+
30+
// otherwise, reset the swapped flag so that it
31+
// can be used in the next stage
32+
swapped = false;
33+
34+
// move the end point back by one, because
35+
// item at the end is in its rightful spot
36+
--end;
37+
38+
// from right to left, doing the
39+
// same comparison as in the previous stage
40+
for (int i = end - 1; i >= start; --i) {
41+
if (a[i] > a[i + 1]) {
42+
swap(a[i], a[i + 1]);
43+
swapped = true;
44+
}
45+
}
46+
47+
// increase the starting point, because
48+
// the last stage would have moved the next
49+
// smallest number to its rightful spot.
50+
++start;
51+
}
52+
}
53+
54+
/* Prints the array */
55+
void printArray(int a[], int n)
56+
{
57+
for (int i = 0; i < n; i++)
58+
printf("%d ", a[i]);
59+
printf("\n");
60+
}
61+
62+
// Driver code
63+
int main()
64+
{
65+
int arr[] = { 5, 1, 4, 2, 8, 0, 2 };
66+
int n = sizeof(arr) / sizeof(arr[0]);
67+
CocktailSort(a, n);
68+
printf("Sorted array :\n");
69+
printArray(a, n);
70+
return 0;
71+
}

0 commit comments

Comments
 (0)