public class BubbleSort
{
public static void Execute(int[] arr)
{
if(arr == null || arr.Length < 2) return;
for (int i = 0; i < arr.Length - 1; i ++)
{
// 使用标识可以让数组的有序部分不再进行比较
bool isSorted = true;
int sortBorder = arr.Length - i -1;
for (int j = 0; j < arr.Length - i - 1; j ++)
{
if (arr[j] > arr[j + 1])
{
Swap(arr, j + 1, j);
isSorted = false;
// 更新最后一次交换的位置,作为下一轮比较的边界
sortBorder = j;
}
}
if (isSorted) break;
}
}
private static void Swap(int[] arr, int left, int right)
{
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
}
public class Client
{
public static void Main()
{
int[] arr = new int[] { 1, 5, 2, 4, 3, 7, 1, 9, 3, 2 };
Console.WriteLine("排序前" + string.Join(",", arr));
BubbleSort.Execute(arr);
Console.WriteLine("排序后" + string.Join(",", arr));
}
}
【算法】冒泡排序(优化)
于 2025-10-17 11:16:36 首次发布
AgenticAI·十月创作之星挑战赛
10w+人浏览
1k人参与
