用Java写一个简单的冒泡排序
时间: 2023-03-29 12:03:29 浏览: 53
好的,我可以回答这个问题。以下是用 Java 写的简单冒泡排序的代码:
```
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 3, 1, 6};
int temp;
for (int i = ; i < arr.length - 1; i++) {
for (int j = ; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (int i = ; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
```
这个程序使用了冒泡排序算法对数组进行排序。在冒泡排序中,我们比较相邻的元素,如果它们的顺序不正确,就交换它们的位置,直到整个数组都被排序。
相关问题
用java写一个双向冒泡排序
好的,以下是双向冒泡排序的Java实现代码:
```
public class BubbleSort {
public static void bidirectionalBubbleSort(int[] arr) {
int left = 0, right = arr.length - 1;
while (left < right) {
for (int i = left; i < right; i++) {
if (arr[i] > arr[i + 1]) {
swap(arr, i, i + 1);
}
}
right--;
for (int j = right; j > left; j--) {
if (arr[j] < arr[j - 1]) {
swap(arr, j, j - 1);
}
}
left++;
}
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args) {
int[] arr = {5, 2, 6, 1, 3, 9, 4};
bidirectionalBubbleSort(arr);
System.out.println(Arrays.toString(arr)); // 输出 [1, 2, 3, 4, 5, 6, 9]
}
}
```
希望以上代码可以帮助到您。
用java写一个冒泡排序
好的,以下是用 Java 写的冒泡排序代码:
```java
public class BubbleSort {
public static void main(String[] args) {
// 定义一个数组
int[] arr = {3, 1, 6, 2, 9, 0, 4, 8, 5, 7};
// 冒泡排序
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// 交换相邻两个数的位置
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// 输出排序后的数组
for (int num : arr) {
System.out.print(num + " ");
}
}
}
```
以上代码中,我们定义了一个数组 `arr`,并且对其进行了冒泡排序。在冒泡排序的过程中,我们通过两层循环来比较相邻的两个数,如果前一个数比后一个数大,则交换它们的位置。最终输出排序后的结果。