生成一个冒泡排序的代码
时间: 2023-11-27 14:53:57 浏览: 37
以下是Python语言的冒泡排序代码:
```
def bubbleSort(arr):
n = len(arr)
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print ("排序后的数组:")
for i in range(len(arr)):
print ("%d" %arr[i]),
```
该代码使用了两个嵌套的循环来进行排序,外层循环从数组的第一个元素开始到倒数第二个元素结束,内层循环从数组的第一个元素开始到当前外层循环所在的位置的前一个元素结束。在每次内层循环中,如果相邻两个元素的顺序不对,则将它们交换位置。最终,所有的元素将按升序排列。
相关问题
用c++生成一个冒泡排序代码
好的,以下是用C语言编写的冒泡排序代码:
```c
#include <stdio.h>
int main() {
int arr[] = {5, 2, 7, 1, 0, 9, 8, 4, 3, 6};
int n = sizeof(arr)/sizeof(arr[0]);
for (int i = 0; i < n-1; i++) {
for (int 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;
}
}
}
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
该代码实现了冒泡排序算法,可对一个整型数组进行排序。希望对你有所帮助。
用C语言生成一个冒泡排序代码
以下是一个简单的C语言冒泡排序代码:
```c
#include <stdio.h>
void bubbleSort(int arr[], int n) {
int i, j, 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() {
int arr[] = { 64, 34, 25, 12, 22, 11, 90 };
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
这个代码使用了嵌套的for循环来执行冒泡排序。在外层循环中,它遍历了数组中的每个元素,而在内层循环中,它比较了相邻的两个元素,并且如果它们不是按顺序排列的,就交换它们的位置。这个过程一直持续到数组中的所有元素都按顺序排列为止。
相关推荐
![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)