Cocktail Shaker Sort

Cocktail shaker sort, also known as bidirectional bubble sort, cocktail sort, shaker sort, ripple sort, shuffle sort, or shuttle sort, is a variation of bubble sort that is both a stable sorting algorithm and a comparison sort. The algorithm differs from a bubble sort in that it sorts in both directions on each pass through the list. This sorting algorithm is only marginally more difficult to implement than a bubble sort, and solves the problem of turtles in bubble sorts. It provides only marginal performance improvements, and does not improve asymptotic performance; like the bubble sort.



									Private Shared Sub Swap(ByRef a As Integer, ByRef b As Integer)
	a = a Xor b
	b = b Xor a
	a = a Xor b
End Sub

Public Shared Sub CocktailSort(ByRef data As Integer())
	While True
		Dim flag As Boolean
		Dim start As Integer() = {1, data.Length - 1}
		Dim [end] As Integer() = {data.Length, 0}
		Dim inc As Integer() = {1, -1}

		For it As Integer = 0 To 1
			flag = True

			Dim i As Integer = start(it)
			While i <> [end](it)
				If data(i - 1) > data(i) Then
					Swap(data(i - 1), data(i))
					flag = False
				End If
				i += inc(it)
			End While

			If flag Then
				Return
			End If
		Next
	End While
End Sub
								


Example

									Dim data As Integer() = {-1, 25, -58964, 8547, -119, 0, 78596}
CocktailSort(data)
								


Output

									-58964
-119
-1
0
25
8547
78596