//冒泡排序
public static void BubbleSort(int[] myArray)
{
for (int i = 0; i < myArray.Length - 1; i++)
{
for (int j = 0; j < myArray.Length - 1 - i; j++)
{
if (myArray[j] < myArray[j + 1])
{
Swap(ref myArray[j], ref myArray[j+1]);
}
}
}
}
//快速排序
public static void QuickSort(int[] myArray, int leftIndex, int rightIndex)
{
int i, j, s;
if (leftIndex < rightIndex)
{
i = leftIndex - 1;
j = rightIndex + 1;
s = myArray[(i + j) / 2];
while (true)
{
//修改此处,改变排序次序
while (myArray[++i] < s) ;
while (myArray[--j] > s) ;
if (i >= j)
{
break;
}
Swap(ref myArray[i], ref myArray[j]);
}
QuickSort(myArray, leftIndex, i - 1);
QuickSort(myArray, j + 1, rightIndex);
}
}
//鸡尾酒排序
public static void CockTailSort(int[] myArray)
{
int leftIndex, rightIndex, index;
leftIndex = 0;
rightIndex = myArray.Length - 1;
index = leftIndex;
while (rightIndex > leftIndex)
{
for (int i = leftIndex; i < rightIndex; i++)
{
if (myArray[i] > myArray[i + 1])
{
Swap(ref myArray[i], ref myArray[i + 1]);
index = i;
}
}
rightIndex = index;
for (int i = rightIndex; i > leftIndex; i--)
{
if (myArray[i] < myArray[i - 1])
{
Swap(ref myArray[i], ref myArray[i - 1]);
index = i;
}
}
leftIndex = index;
}
}
//选择排序
public static void SelectSort(int[] myArray)
{
int smallest;
for (int i = 0; i < myArray.Length - 1; i++)
{
smallest = i;
for (int j = i + 1; j < myArray.Length; j++)
{
if (myArray[j] < myArray[smallest])
{
smallest = j;
}
}
Swap(ref myArray[i], ref myArray[smallest]);
}
}
//插入排序
public static void InsertSort(int[] myArray)
{
int temp;
for (int i = 1; i < myArray.Length; i++)
{
temp = myArray[i];
int j = i - 1;
while (j >= 0 && myArray[j] > temp)
{
myArray[j + 1] = myArray[j];
j--;
}
myArray[j + 1] = temp;
}
}
private static void Swap(ref int left, ref int right)
{
int temp;
temp = left;
left = right;
right = temp;
}
C# 排序算法
最新推荐文章于 2024-07-19 15:13:08 发布