刚刚练习了冒泡算法,趁热打铁,练习鸡尾酒算法。Cocktail!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 鸡尾酒排序算法
{
class Program
{
static void Main(string[] args)
{
int[] arr1 = new int[] { 2, 5, 3, 18, 23, 12, 13, 16, 11 };
Cocktail(arr1);
for (int i = 0; i < arr1.Length; i++)
{
Console.Write(arr1[i] + " ");
}
Console.Read();
}
static void change(ref int left, ref int right)//change方法来作值交换
{
int temp;
temp = left;
left = right;
right = temp;
}
static void Cocktail(int[] arr)//鸡尾酒排序
{
int up = arr.Length - 1;//设置排序上限
int low = 0;//设置排序下限
while (low < up)
{
for (int i = low; i < up; i++)
{
if (arr[i] <= arr[i + 1])
{
continue;
}
else
{
change(ref arr[i], ref arr[i + 1]);
}
}
up--;
for (int j = up; j > low; j--)
{
if (arr[j] >= arr[j - 1])
{
continue;
}
else
{
change(ref arr[j], ref arr[j - 1]);
}
low++;
}
}
}
}
}