以下是C#代码实现冒泡排序:

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])
            {
                // 交换arr[j]和arr[j+1]
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

使用示例:

int[] arr = new int[] { 5, 2, 8, 3, 1, 6 };
BubbleSort(arr);
foreach (int num in arr)
{
    Console.Write(num + " ");
}

输出:

1 2 3 5 6 8
用C#写一个冒泡排序

原文地址: https://www.cveoy.top/t/topic/zNl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录