8000 Merge pull request #1572 from tanishqawasthi/patch-3 · kishore-code/Algorithms-1@7b32ff2 · GitHub
[go: up one dir, main page]

Skip to content

Commit 7b32ff2

Browse files
authored
Merge pull request VAR-solutions#1572 from tanishqawasthi/patch-3
Create cscocktail.cs
2 parents decfb61 + b50d6c0 commit 7b32ff2

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

Sorting/Cocktail/cscocktail.cs

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

0 commit comments

Comments
 (0)
0