using System;
class Program
{
static void Main()
{
int[] array = { 64, 34, 25, 12, 22, 11, 90 };
Console.WriteLine("排序前的数组:");
PrintArray(array);
BubbleSort(array);
Console.WriteLine("排序后的数组:");
PrintArray(array);
}
static void BubbleSort(int[] arr)
{
int n = arr.Length;
for (int i = 0; i < n - 1; i++)
{
// 提前退出标志位
bool swapped = false;
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;
swapped = true;
}
}
// 如果没有发生交换,说明数组已经有序,提前退出
if (!swapped)
break;
}
}
static void PrintArray(int[] arr)
{
foreach (int num in arr)
{
Console.Write(num + " ");
}
Console.WriteLine();
}
}
主程序 (Main 方法):
array 并初始化。BubbleSort 方法对数组进行排序。冒泡排序 (BubbleSort 方法):
n。swapped 标志位来检测是否发生了交换,如果没有发生交换则提前退出循环,优化排序过程。打印数组 (PrintArray 方法):
上一篇:c# 遍历文件夹
下一篇:c# thread.sleep
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站