Skip to content

Commit 9d8ba08

Browse files
Akshamathuva4
authored andcommitted
Added Cocktail Sort implementation in C++ (thuva4#536)
* Create cocktail_sort.cpp * Update cocktail_sort.cpp * Rename Cocktail_Sort/Cpp/cocktail_sort.cpp to CocktailSort/Cpp/CocktailSort.cpp
1 parent 5628864 commit 9d8ba08

1 file changed

Lines changed: 76 additions & 0 deletions

File tree

CocktailSort/Cpp/CocktailSort.cpp

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

0 commit comments

Comments
 (0)