冒泡排序是一种简单的排序算法,它依次比较相邻的两个元素,如果它们的顺序不正确,则交换它们。重复这个过程,直到整个数组按照升序排列。以下是用C#编写的冒泡排序的实现。

using System;

class BubbleSort
{
    static void Main()
    {
        int[] array = { 5, 2, 8, 1, 4 };

        Console.WriteLine("原始数组:");
        PrintArray(array);

        BubbleSortAlgorithm(array);

        Console.WriteLine("\n排序后的数组:");
        PrintArray(array);
    }

    static void BubbleSortAlgorithm(int[] array)
    {
        int n = array.Length;
        for (int i = 0; i < n - 1; i++)
        {
            for (int j = 0; j < n - i - 1; j++)
            {
                if (array[j] > array[j + 1])
                {
                    // 交换两个元素
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
    }

    static void PrintArray(int[] array)
    {
        foreach (int num in array)
        {
            Console.Write(num + " ");
        }
    }
}

这个程序首先定义了一个整数数组,然后调用BubbleSortAlgorithm方法进行排序。BubbleSortAlgorithm方法使用两个嵌套循环来比较相邻的元素并交换它们,直到整个数组按照升序排列为止。最后,程序调用PrintArray方法来打印排序后的数组

用C#写冒泡排序

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

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