冒泡法排序将n个数从小到大排序
时间: 2023-12-12 22:05:27 浏览: 64
冒泡法排序的基本思想是从头到尾比较相邻两个元素的大小,如果前一个元素比后一个元素大,则交换这两个元素的位置,一轮比较下来,最大的元素就会被交换到最后面。然后再从头开始进行相邻元素的比较和交换,直到所有元素都排好序为止。
以下是冒泡法排序的 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
```
相关问题
冒泡法排序将n个数从小到大排序 用c++实现
冒泡排序的C++实现代码如下:
```c++
#include <iostream>
using namespace std;
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]) {
swap(arr[j], arr[j + 1]);
}
}
}
}
int main() {
int arr[] = {5, 2, 8, 3, 1, 6};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
```
输出结果为:1 2 3 5 6 8
利用冒泡排序法,实现5个数从小到大排序
好的,我可以回答这个问题。以下是使用冒泡排序算法将五个数从小到大排序的示例代码:
```
#include <stdio.h>
#define SIZE 5
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j+1])
{
swap(&arr[j], &arr[j+1]);
}
}
}
}
int main()
{
int arr[SIZE] = {5, 3, 9, 1, 7};
int i;
printf("Before sorting: ");
for (i = 0; i < SIZE; i++)
{
printf("%d ", arr[i]);
}
bubbleSort(arr, SIZE);
printf("\nAfter sorting: ");
for (i = 0; i < SIZE; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
```
希望能够帮助您!
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)