C# 冒泡排序算法实现 - 代码示例与解析
以下是C#实现的冒泡排序代码:
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])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
使用方法:
int[] arr = { 23, 45, 12, 78, 56 };
BubbleSort(arr);
foreach (int i in arr)
{
Console.Write(i + " ");
}
输出结果:
12 23 45 56 78
原文地址: https://www.cveoy.top/t/topic/mU5C 著作权归作者所有。请勿转载和采集!