以下是一段C语言的冒泡算法:

#include <stdio.h>

void bubbleSort(int arr[], int n) {
    int i, j, temp;
    for (i = 0; i < n-1; i++) {
        for (j = 0; j < n-i-1; j++) {
            if (arr[j] > arr[j+1]) {
                temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr)/sizeof(arr[0]);
    bubbleSort(arr, n);
    printf("Sorted array: \n");
    for (int i=0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
    return 0;
}

该程序中,bubbleSort函数实现了冒泡排序算法,通过两层循环遍历数组中的元素,如果相邻的元素大小不符合要求则交换位置,直到整个数组中的元素都被排序。在主函数中,我们定义了一个整型数组,并通过sizeof运算符计算出数组的长度,然后调用bubbleSort函数对数组进行排序。最后,我们遍历已排序的数组并输出结果。

生成一段C语言的冒泡算法

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

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