编写一个程序,要求使用冒泡排序法将数组中的元素按升序排列。 要求: 使用冒泡排序算法进行排序。 输出排序后的数组。 已知数据:arr = {5, 3, 8, 4, 2}
时间: 2025-07-06 17:49:05 浏览: 15
### 使用 C# 实现冒泡排序算法
为了实现对数组 `{5, 3, 8, 4, 2}` 进行升序排列,可以采用如下所示的冒泡排序算法。此算法通过反复遍历要排序的列表来工作,依次比较相邻元素并对顺序不对的元素进行交换。
```csharp
using System;
class Program {
static void Main(string[] args) {
int[] numbers = {5, 3, 8, 4, 2};
BubbleSort(numbers);
Console.WriteLine("Sorted array:");
foreach (var num in numbers) {
Console.Write(num + " ");
}
}
static void BubbleSort(int[] arr) {
bool swapped;
for (int i = 0; i < arr.Length - 1; i++) {
swapped = false;
for (int j = 0; j < arr.Length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
// If no two elements were swapped by inner loop, then break
if (!swapped) break;
}
}
}
```
这段代码首先定义了一个名为 `numbers` 的整型数组,并调用了 `BubbleSort` 方法对该数组进行了排序处理[^3]。在完成排序之后,程序打印出了已按升序排列好的数组内容。
阅读全文
相关推荐


















