cshap生成一个冒泡排序
时间: 2023-04-08 13:01:23 浏览: 51
可以使用以下代码生成一个冒泡排序:
```
static void BubbleSort(int[] arr)
{
int n = arr.Length;
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
```
相关问题
CShap 鸡尾酒选择排序 源代码
以下是C#语言的鸡尾酒选择排序代码:
```
public static void CocktailSort(int[] array)
{
bool swapped = true;
int start = 0;
int end = array.Length;
while (swapped)
{
swapped = false;
//从左到右进行冒泡排序
for (int i = start; i < end - 1; ++i)
{
if (array[i] > array[i + 1])
{
Swap(ref array[i], ref array[i + 1]);
swapped = true;
}
}
//如果没有交换,则已排序完毕
if (!swapped)
{
break;
}
swapped = false;
//从右到左进行冒泡排序
for (int i = end - 1; i > start; --i)
{
if (array[i] < array[i - 1])
{
Swap(ref array[i], ref array[i - 1]);
swapped = true;
}
}
++start;
}
}
private static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
```
以上代码通过交替进行从左到右和从右到左的冒泡排序来完成鸡尾酒选择排序。在每次循环中,它先从左到右排序,然后从右到左排序,直到没有交换发生为止。
CShap数字字符串排序 源代码
以下是一个用C#编写的数字字符串排序的源代码:
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
string[] numbers = { "10", "9", "100", "200", "50" };
Console.WriteLine("排序前:");
foreach (string number in numbers)
{
Console.Write(number + " ");
}
Array.Sort(numbers, (a, b) => int.Parse(a).CompareTo(int.Parse(b)));
Console.WriteLine("\n排序后:");
foreach (string number in numbers)
{
Console.Write(number + " ");
}
Console.ReadLine();
}
}
该程序首先声明一个包含数字字符串的数组,然后使用Array.Sort方法进行排序。在这个例子中,使用lambda表达式作为比较器来确保以数字方式排序。最后,程序在控制台上打印排序前和排序后的数字字符串。