Cocktail SortCocktail sort is the variation of Bubble Sort which traverses the list in both directions alternatively. It is different from bubble sort in the sense that, bubble sort traverses the list in forward direction only, while this algorithm traverses in forward as well as backward direction in one iteration. AlgorithmIn cocktail sort, one iteration consists of two stages:
The process continues until the list becomes unsorted. ExampleConsider the array A : {8, 2, 3, 1, 9}. Sort the elements of the array using Cocktail sort. Iteration 1:Forward pass : At the end of first forward pass: the largest element of the list is placed at the end. Backward pass: At the end of first backward pass; the smallest element has been placed at the first index of the array. If we have a look at the list produced in the first step; we can find that the list has already been sorted in ascending order but the algorithm will process itself completely. Complexity
C ProgramOutput: printing sorted array : 0 1 2 3 8 10 23 45 C++ ProgramOutput: printing sorted array : 0 1 2 3 8 10 23 45 Java ProgramOutput: printing sorted array : 0 1 2 3 8 10 23 45 C# ProgramOutput: printing sorted array : 0 1 2 3 8 10 23 45 Python ProgramOutput: printing sorted array : 0 1 2 3 8 10 23 45 Rust ProgramOutput: printing sorted array : 0 1 2 3 8 10 23 45 JavaScript ProgramOutput: printing sorted array : 0 1 2 3 8 10 23 45
Next TopicCycle Sort
