浮点数数组的冒泡排序
时间: 2024-05-24 09:09:39 浏览: 19
浮点数数组的冒泡排序是一种简单直观的排序算法,其基本思想是通过比较相邻的元素,将较大的元素交换到右侧,较小的元素交换到左侧,从而实现排序。具体步骤如下:
1. 从数组的第一个元素开始比较相邻的两个元素,如果前面的元素比后面的元素大,则交换这两个元素的位置。
2. 对整个数组重复以上步骤,直到没有任何一对数字需要比较为止。
以下是浮点数数组冒泡排序的示例代码:
```c++
void bubbleSort(float 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]) {
float temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
```
相关问题
用冒泡排序。对12个浮点数,这12个浮点数放在数组,从小到大,c语言程序
好的,下面是使用冒泡排序对12个浮点数进行排序的C语言程序:
```c
#include <stdio.h>
void bubble_sort(float arr[], int size) {
int i, j;
float temp;
for (i = 0; i < size - 1; i++) {
for (j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
float nums[] = {3.14, 2.71, 1.23, 4.56, 0.99, 6.78, 5.43, 8.76, 9.87, 7.65, 10.11, 11.12};
int size = sizeof(nums) / sizeof(nums[0]);
bubble_sort(nums, size);
printf("Sorted array: ");
for (int i = 0; i < size; i++) {
printf("%f ", nums[i]);
}
printf("\n");
return 0;
}
```
这个程序中,我们定义了一个 `bubble_sort` 函数来执行冒泡排序。该函数接受一个浮点数数组和数组大小作为参数,并使用嵌套的循环来比较和交换数组元素,以将它们从小到大排序。在主函数中,我们定义了一个包含12个浮点数的数组,使用 `sizeof` 运算符来计算数组大小,然后调用 `bubble_sort` 函数来对数组进行排序。最后,我们循环遍历排序后的数组,并将其打印出来。
用c语言写,用冒泡法排序,对12个浮点数,这12个浮点数放在数组。从小到大
好的,您可以参考以下代码实现:
```c
#include <stdio.h>
void bubbleSort(float arr[], int n) {
int i, j;
float 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() {
float arr[12] = {1.2, 5.6, 4.3, 0.5, 8.9, 2.4, 3.1, 9.8, 7.6, 6.5, 11.0, 10.3};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%.1f ", arr[i]);
}
return 0;
}
```
在这段代码中,我们定义了一个 `bubbleSort` 函数,它使用了冒泡排序算法对浮点数数组进行排序。然后我们在 `main` 函数中初始化了一个包含 12 个浮点数的数组,并调用 `bubbleSort` 函数对其进行排序。最后输出排序后的数组。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)