编写一个采用冒泡法对n个数由小到大进行排序的函数
时间: 2023-04-11 22:04:52 浏览: 111
以下是一个采用冒泡法对n个数由小到大进行排序的函数:
void bubbleSort(int arr[], int n) {
int i, j;
for (i = 0; i < n-1; i++) {
for (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;
}
}
}
}
其中,arr为待排序的数组,n为数组中元素的个数。函数中使用了两层循环,外层循环控制排序的轮数,内层循环控制每一轮中相邻元素的比较和交换。如果相邻元素的顺序不符合要求,则交换它们的位置,直到所有元素都按照从小到大的顺序排列。
相关问题
编写函数,用冒泡法对10个字符按小到大排序
这里提供Python语言的实现:
```python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
if __name__ == '__main__':
arr = ['c', 'd', 'a', 'f', 'e', 'b', 'j', 'i', 'h', 'g']
print(bubble_sort(arr))
```
输出结果为:
```
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
```
用C语言编写函数,用冒泡法对10个字符按小到大排序
```c
#include <stdio.h>
void bubbleSort(char arr[], int n) {
int i, j;
char 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() {
char arr[] = {'d', 'c', 'a', 'b', 'h', 'g', 'f', 'e', 'i', 'j'};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printf("排序后的字符为:\n");
for (int i = 0; i < n; i++) {
printf("%c ", arr[i]);
}
printf("\n");
return 0;
}
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)