以下是用C#编写的冒泡排序算法:

using System;

class BubbleSort {
    static void Main(string[] args) {
        int[] arr = { 64, 34, 25, 12, 22, 11, 90 };

        Console.WriteLine("Original Array:");
        PrintArray(arr);

        BubbleSortAlgorithm(arr);

        Console.WriteLine("Sorted Array:");
        PrintArray(arr);
    }

    static void BubbleSortAlgorithm(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;
                }
            }
        }
    }

    static void PrintArray(int[] arr) {
        foreach (int i in arr) {
            Console.Write(i + " ");
        }
        Console.WriteLine();
    }
}

在这个程序中,我们首先声明一个整数数组,并将其传递到冒泡排序函数中。然后,在函数中,我们使用两个嵌套的循环来遍历整个数组,并比较相邻的元素以查看它们是否需要交换。如果需要交换,我们使用一个临时变量来交换元素的位置。最后,我们打印排序后的数组。

用c#写一个冒泡

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

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