Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Sorting
  • MCQs on Sorting
  • Tutorial on Sorting
  • Bubble Sort
  • Quick Sort
  • Merge Sort
  • Insertion Sort
  • Selection Sort
  • Heap Sort
  • Sorting Complexities
  • Radix Sort
  • ShellSort
  • Counting Sort
  • Bucket Sort
  • TimSort
  • Bitonic Sort
  • Uses of Sorting Algorithm
Open In App
Next Article:
C++ Program for ShellSort
Next article icon

C++ Program for Cocktail Sort

Last Updated : 13 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Cocktail Sort is a variation of Bubble sort. The Bubble sort algorithm always traverses elements from left and moves the largest element to its correct position in first iteration and second largest in second iteration and so on. Cocktail Sort traverses through a given array in both directions alternatively. 
Algorithm: 
Each iteration of the algorithm is broken up into 2 stages: 
 

  1. The first stage loops through the array from left to right, just like the Bubble Sort. During the loop, adjacent items are compared and if value on the left is greater than the value on the right, then values are swapped. At the end of first iteration, largest number will reside at the end of the array.
  2. The second stage loops through the array in opposite direction- starting from the item just before the most recently sorted item, and moving back to the start of the array. Here also, adjacent items are compared and are swapped if required.

 

CPP




// C++ implementation of Cocktail Sort
#include <bits/stdc++.h>
using namespace std;
 
// Sorts array a[0..n-1] using Cocktail sort
void CocktailSort(int a[], int n)
{
 bool swapped = true;
 int start = 0;
 int end = n - 1;
 
 while (swapped) {
  // reset the swapped flag on entering
  // the loop, because it might be true from
  // a previous iteration.
  swapped = false;
 
  // loop from left to right same as
  // the bubble sort
  for (int i = start; i < end; ++i) {
   if (a[i] > a[i + 1]) {
    swap(a[i], a[i + 1]);
    swapped = true;
   }
  }
 
  // if nothing moved, then array is sorted.
  if (!swapped)
   break;
 
  // otherwise, reset the swapped flag so that it
  // can be used in the next stage
  swapped = false;
 
  // move the end point back by one, because
  // item at the end is in its rightful spot
  --end;
 
  // from right to left, doing the
  // same comparison as in the previous stage
  for (int i = end - 1; i >= start; --i) {
   if (a[i] > a[i + 1]) {
    swap(a[i], a[i + 1]);
    swapped = true;
   }
  }
 
  // increase the starting point, because
  // the last stage would have moved the next
  // smallest number to its rightful spot.
  ++start;
 }
}
 
/* Prints the array */
void printArray(int a[], int n)
{
 for (int i = 0; i < n; i++)
  printf("%d ", a[i]);
 printf("\n");
}
 
// Driver code
int main()
{
 int arr[] = { 5, 1, 4, 2, 8, 0, 2 };
 int n = sizeof(arr) / sizeof(arr[0]);
 CocktailSort(arr, n);
 printf("Sorted array :\n");
 printArray(arr, n);
 return 0;
}
 
 
Output: 
Sorted array : 0 1 2 2 4 5 8

 

Worst and Average Case Time Complexity: O(n2). 
Best Case Time Complexity: O(n). The best-case occurs when the array is already sorted.
Auxiliary Space: O(1)

Please refer complete article on Cocktail Sort for more details!
 



Next Article
C++ Program for ShellSort
author
kartik
Improve
Article Tags :
  • C++ Programs
  • DSA
  • Sorting
Practice Tags :
  • Sorting

Similar Reads

  • C++ Program for Comb Sort
    Comb Sort is mainly an improvement over Bubble Sort. Bubble sort always compares adjacent values. So all inversions are removed one by one. Comb Sort improves on Bubble Sort by using gap of size more than 1. The gap starts with a large value and shrinks by a factor of 1.3 in every iteration until it
    2 min read
  • C++ Program for Bitonic Sort
    Bitonic Sequence A sequence is called Bitonic if it is first increasing, then decreasing. In other words, an array arr[0..n-i] is Bitonic if there exists an index i where 0<=i<=n-1 such that x0 <= x1 …..<= xi and xi >= xi+1….. >= xn-1 A sequence, sorted in increasing order is consi
    4 min read
  • C++ Program for Bitonic Sort
    Bitonic Sequence: A sequence is called Bitonic if it is first increasing, then decreasing. In other words, an array arr[0..n-i] is Bitonic if there exists an index i where 0<=i<=n-1 such that x0 <= x1 …..<= xi and xi >= xi+1….. >= xn-1 A sequence, sorted in increasing order is cons
    4 min read
  • C++ Program for ShellSort
    In shellSort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every h'th element is sorted. C/C++ Code // C++ implementation of Shell Sort #include <iostream> /* function to sort arr using
    2 min read
  • C++ Program for Heap Sort
    Heap sort is a comparison-based sorting technique based on the Binary Heap data structure. It is similar to the selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for the remaining element. Recommended PracticeHeap SortTry It!
    3 min read
  • C++ Program for Quick Sort
    Quick Sort is one of the most efficient sorting algorithms available to sort the given dataset. It is known for its efficiency in handling large datasets which made it a go-to choice for programmers looking to optimize their code. In C++, the STL's sort() function uses a mix of different sorting alg
    4 min read
  • C++ Program For Merge Sort
    Merge Sort is a comparison-based sorting algorithm that uses divide and conquer paradigm to sort the given dataset. It divides the dataset into two halves, calls itself for these two halves, and then it merges the two sorted halves. In this article, we will learn how to implement merge sort in a C++
    4 min read
  • C++ Program For Insertion Sort
    Insertion sort is a simple sorting algorithm that works by dividing the array into two parts, sorted and unsorted part. In each iteration, the first element from the unsorted subarray is taken and it is placed at its correct position in the sorted array. In this article, we will learn to write a C++
    3 min read
  • C++ Program For Selection Sort
    The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. The subarray which is already sorted. Remaining subarray which is unsorted.
    4 min read
  • Structure of C++ Program
    The C++ program is written using a specific template structure. The structure of the program written in C++ language is as follows: Documentation Section:This section comes first and is used to document the logic of the program that the programmer going to code.It can be also used to write for purpo
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences