生成C#的冒泡排序
时间: 2023-07-12 19:10:03 浏览: 57
当然,以下是C#实现冒泡排序的代码:
```csharp
public 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])
{
// 交换 arr[j] 和 arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
```
在该代码中,我们定义了一个名为`BubbleSort`的公共方法,它接受一个整数数组作为参数。内部实现了一个双重循环用于执行冒泡排序。这个排序算法的时间复杂度为O(n²)。
相关问题
C#冒泡排序lambda
以下是使用Lambda表达式实现的C#冒泡排序的示例代码:
```csharp
public static void BubbleSort<T>(IList<T> sortArray, Func<T, T, bool> comparison)
{
int n = sortArray.Count;
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (comparison(sortArray[j], sortArray[j + 1]))
{
T temp = sortArray[j];
sortArray[j] = sortArray[j + 1];
sortArray[j + 1] = temp;
}
}
}
}
```
使用Lambda表达式作为比较函数,可以根据需要自定义排序规则。比较函数接受两个参数,并返回一个bool值,表示第一个参数是否应该排在第二个参数之前。
以下是使用Lambda表达式进行冒泡排序的示例代码:
```csharp
List<int> numbers = new List<int> { 5, 2, 8, 1, 9 };
BubbleSort(numbers, (a, b) => a > b);
foreach (int number in numbers)
{
Console.WriteLine(number);
}
```
这段代码将列表中的数字按照从小到大的顺序进行排序,并输出排序后的结果。
c# 冒泡排序
以下是C#中实现冒泡排序的示例代码:
```csharp
public 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])
{
// 交换 arr[j] 和 arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
```
在这个示例中,我们定义了一个名为`BubbleSort`的静态方法,它接受一个整数数组作为参数,并使用冒泡排序算法对数组进行排序。内部循环遍历数组并比较相邻的元素,如果它们不是按照升序排列的,则交换它们的位置。
要使用该方法对整数数组进行排序,只需调用`BubbleSort`并传入要排序的数组即可:
```csharp
int[] arr = { 64, 34, 25, 12, 22, 11, 90 };
BubbleSort(arr);
Console.WriteLine("排序后的数组:");
foreach (int i in arr)
{
Console.Write(i + " ");
}
```
输出结果为:
```
排序后的数组:
11 12 22 25 34 64 90
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)