java编写气泡排序代码
时间: 2023-04-01 14:01:44 浏览: 64
可以的,以下是 Java 编写气泡排序的代码:
```java
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = ; i < n - 1; i++) {
for (int j = ; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
```
这段代码实现了气泡排序,可以对传入的整型数组进行排序。
相关问题
起泡排序代码
以下是起泡排序(Bubble Sort)的 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 = [64, 34, 25, 12, 22, 11, 90]
print(bubble_sort(arr))
```
输出结果:
```
[11, 12, 22, 25, 34, 64, 90]
```
原理:冒泡排序是一种简单的排序算法,它重复地遍历要排序的数列,一次比较两个元素,如果它们的顺序错误就将它们交换过来。遍历数列的工作是重复地进行直到没有再需要交换的元素。
dev-c++气泡排序简单代码
以下是使用 C++ 编写的气泡排序代码:
```cpp
#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[] = { 64, 34, 25, 12, 22, 11, 90 };
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
在这个例子中,我们定义了一个 `bubbleSort` 函数,它接受一个整数数组和数组的大小作为参数,并使用气泡排序算法对数组进行排序。在主函数中,我们创建了一个整数数组并将其传递给 `bubbleSort` 函数。然后,我们输出排序后的数组。