请给我写一段冒泡排序的代码
时间: 2023-03-13 22:00:49 浏览: 43
答:for(int i=0; i<n-1; i++) {
for(int j=0; j<n-i-1; j++) {
if (arr[j] > arr[j+1]) {
int tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
}
}
相关问题
给我写一段冒泡排序c语言代码
好的,以下是冒泡排序的 C 语言代码:
```c
#include <stdio.h>
void bubble_sort(int arr[], int n) {
int i, j, temp;
for (i = ; i < n - 1; i++) {
for (j = ; 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[] = {5, 2, 8, 3, 1, 6};
int n = sizeof(arr) / sizeof(arr[]);
bubble_sort(arr, n);
printf("排序后的数组:");
for (int i = ; i < n; i++) {
printf("%d ", arr[i]);
}
return ;
}
```
希望能对您有所帮助!
请给我写一段冒泡排序 用Python
当然,我可以为您写一段冒泡排序的 Python 代码,请见下文:
```
def bubble_sort(lst):
n = len(lst)
for i in range(n-1):
for j in range(n-i-1):
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
return lst
# 示例
lst = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print(bubble_sort(lst))
```
这段代码可以对一个列表进行冒泡排序,输出结果将会是:
```
[17, 20, 26, 31, 44, 54, 55, 77, 93]
```
希望这对您有所帮助。
相关推荐
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.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)