用C语言写一段程序实现冒泡排序
以下是用C语言实现冒泡排序的程序:
#include <stdio.h>
void bubbleSort(int arr[], int n) {
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;
}
}
}
}
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的函数,该函数使用冒泡排序算法对传入的数组进行排序。然后,在主函数中定义了一个整数数组arr,并计算数组的大小。接下来,调用bubbleSort函数对数组进行排序,并使用循环遍历数组并打印排序后的结果。最后,程序返回0表示正常结束
原文地址: https://www.cveoy.top/t/topic/indF 著作权归作者所有。请勿转载和采集!