用 C#写个冒泡排序
冒泡排序(Bubble Sort)是一种简单的排序算法。它重复地遍历待排序的列表,比较相邻的两个元素,如果它们的顺序错误就交换它们的位置。遍历列表的工作是重复地进行直到没有再需要交换,也就是说列表已经排序完成。
以下是一个使用冒泡排序算法对一个整数列表进行排序的C#示例:
```csharp
using System;
using System.Collections.Generic;
namespace BubbleSort
{
class Program
{
static void Main(string[] args)
{
int[] unsortedArray = { 44, 23, 77, 11, 99, 55 };
int[] sortedArray = BubbleSort(unsortedArray);
Console.WriteLine("Unsorted Array:");
PrintArray(unsortedArray);
Console.WriteLine("\nSorted Array:");
PrintArray(sortedArray);
}
static int[] 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;
}
}
}
return arr;
}
static void PrintArray(int[] arr)
{
foreach (int value in arr)
{
Console.WriteLine(value);
}
}
}
}
```
在这个示例中,我们首先创建了一个待排序的整数数组 `unsortedArray`。然后,调用 `BubbleSort` 函数对其进行排序,并将排序后的数组存储在 `sortedArray` 中。最后,使用 `PrintArray` 函数分别打印排序前后的数组。
因篇幅问题不能全部显示,请点此查看更多更全内容