MCPcopy Create free account
hub / github.com/codemistic/Data-Structures-and-Algorithms / CocktailSort

Function CocktailSort

CPP/sorting/Cocktail Sort.cpp:6–53  ·  view source on GitHub ↗

Sorts array a[0..n-1] using Cocktail sort

Source from the content-addressed store, hash-verified

4
5// Sorts array a[0..n-1] using Cocktail sort
6void CocktailSort(int a[], int n)
7{
8bool swapped = true;
9int start = 0;
10int end = n - 1;
11
12while (swapped) {
13// reset the swapped flag on entering
14// the loop, because it might be true from
15// a previous iteration.
16swapped = false;
17
18// loop from left to right same as
19// the bubble sort
20for (int i = start; i < end; ++i) {
21if (a[i] > a[i + 1]) {
22 swap(a[i], a[i + 1]);
23 swapped = true;
24}
25}
26
27// if nothing moved, then array is sorted.
28if (!swapped)
29break;
30
31// otherwise, reset the swapped flag so that it
32// can be used in the next stage
33swapped = false;
34
35// move the end point back by one, because
36// item at the end is in its rightful spot
37--end;
38
39// from right to left, doing the
40// same comparison as in the previous stage
41for (int i = end - 1; i >= start; --i) {
42if (a[i] > a[i + 1]) {
43 swap(a[i], a[i + 1]);
44 swapped = true;
45}
46}
47
48// increase the starting point, because
49// the last stage would have moved the next
50// smallest number to its rightful spot.
51++start;
52}
53}
54
55/* Prints the array */
56void printArray(int a[], int n)

Callers 1

mainFunction · 0.85

Calls 1

swapFunction · 0.70

Tested by

no test coverage detected