以下是一段使用冒泡排序算法进行排序的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]);
    }
    return 0;
}

该代码使用冒泡排序算法对一个整数数组进行排序。冒泡排序的基本思想是多次比较相邻的两个元素,如果它们的顺序错误,则交换它们。通过多次遍历数组,每次遍历都能将当前最大的元素移动到数组的最后。最终,数组将按升序排序。

在上述代码中,bubbleSort函数用于实现冒泡排序算法。它接受一个整数数组和数组的大小作为参数,并在原地对数组进行排序。

main函数定义了一个整数数组,并计算数组的大小。然后,它调用bubbleSort函数对数组进行排序,并使用printf函数打印排序后的数组。

该代码的输出结果为:11 12 22 25 34 64 90,即排序后的数组

C语言编程 排序代码

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

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