You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
49 lines
1.0 KiB
49 lines
1.0 KiB
#include <stdio.h>
|
|
|
|
// 函数原型声明
|
|
void bubbleSort(int arr[], int n);
|
|
|
|
int main() {
|
|
// 固定数组大小为3
|
|
int n = 3;
|
|
int arr[3];
|
|
|
|
// 获取用户输入数组元素
|
|
for (int i = 0; i < n; i++) {
|
|
scanf("%d", &arr[i]);
|
|
}
|
|
|
|
// 输出排序前的数组
|
|
printf("输出排序前的数组: ");
|
|
for (int i = 0; i < n; i++) {
|
|
printf("%d ", arr[i]);
|
|
}
|
|
printf("\n");
|
|
|
|
// 调用冒泡排序函数
|
|
bubbleSort(arr, n);
|
|
|
|
// 输出排序后的数组
|
|
printf("输出排序后的数组: ");
|
|
for (int i = 0; i < n; i++) {
|
|
printf("%d ", arr[i]);
|
|
}
|
|
printf("\n");
|
|
|
|
return 0;
|
|
}
|
|
|
|
// 冒泡排序函数
|
|
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;
|
|
}
|
|
}
|
|
}
|
|
}
|