Table of content

## Cocktail Sort in Kotlin

Cocktail sort is the variation of Bubble Sort which traverses the list in both directions alternatively. It is different from a bubble sort in the sense that, bubble sort traverses the list in forward direction only, while cocktail sort algorithm traverses in forward as well as backward direction in one iteration

Much like the bubble sort, cocktail sort has very little relevance in the real world and is mainly used to teach algorithms.

Cocktail sort is at its fastest when it can reach a sorted list with a minimal number of passes. Since only adjacent elements are swapped, this means that cocktail sort performs best when elements are physically nearby their sorted positions.
• The first stage loop through the array like bubble sort from left to right. The adjacent elements are compared and if the left element is greater than the right element, then we swap those elements. The largest element of the list is placed at the end of the array in the forward pass.
• The second stage loop through the array from the right most unsorted element to the left. The adjacent elements are compared and if the right element is smaller than the left element then, we swap those elements. The smallest element of the list is placed at the beginning of the array in backward pass.

Complete program for Cocktail sort in kotlin

``````fun cocktailSort(a: IntArray) {
fun swap(i: Int, j: Int) {
val temp = a[i]
a[i] = a[j]
a[j] = temp
}
do {
var swapped = false
for (i in 0 until a.size - 1)
if (a[i] > a[i + 1]) {
swap(i, i + 1)
swapped = true
}
if (!swapped) break
swapped = false
for (i in a.size - 2 downTo 0)
if (a[i] > a[i + 1]) {
swap(i, i + 1)
swapped = true
}
}while (swapped)
}

fun main(args: Array<String>) {
val arr = intArrayOf(4, 65, 2, -31, 0, 99, 2, 83, 782, 1)

cocktailSort(arr)
println(arr.contentToString())
}``````

Output of the Cocktail sort in kotlin

``[-31, 0, 1, 2, 2, 4, 65, 83, 99, 782]``
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions