编写用冒泡排序法对数组中的数据从小到大排序
时间: 2024-04-29 08:26:49 浏览: 18
好的,这个问题很简单,下面是冒泡排序法的 Python 代码实现:
```python
def bubble_sort(arr):
n = len(arr)
# 遍历所有数组元素
for i in range(n):
# Last i elements are already sorted
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
# 测试代码
arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr)
print("排序后的数组:")
for i in range(len(arr)):
print("%d" %arr[i]),
```
输出结果为:
```
排序后的数组:
11
12
22
25
34
64
90
```
相关问题
编写函数用冒泡排序法对数组中的数据进行从小到大的排序
以下是用Python语言编写的冒泡排序函数,可以实现对数组中的数据进行从小到大的排序:
```python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
```
其中,arr为待排序的数组,n为数组的长度。在函数中,使用了两层循环,外层循环控制排序的轮数,内层循环用于比较相邻的元素并进行交换。如果前一个元素比后一个元素大,则交换它们的位置,这样每一轮排序都会将最大的元素“冒泡”到数组的末尾。最终,经过n轮排序后,数组中的元素就会按照从小到大的顺序排列。
c语言用冒泡排序法对数组中的数据从小到大排列
好的,下面是 c 语言用冒泡排序法对数组中的数据从小到大排列的代码实现:
```c
#include <stdio.h>
void bubble_sort(int arr[], int len)
{
int i, j, temp;
for (i = 0; i < len - 1; i++) {
for (j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main()
{
int arr[] = {5, 2, 8, 3, 1, 7, 9, 4, 6};
int len = sizeof(arr) / sizeof(arr[0]);
int i;
printf("排序前数组序列为:");
for (i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
printf("\n");
bubble_sort(arr, len);
printf("排序后数组序列为:");
for (i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
输出结果为:
```
排序前数组序列为:5 2 8 3 1 7 9 4 6
排序后数组序列为:1 2 3 4 5 6 7 8 9
```
希望能够帮助你解决问题!
相关推荐
![](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)