可以使用java写一个冒泡排序吗
时间: 2023-09-10 22:06:16 浏览: 39
可以的,下面是一个使用Java编写的冒泡排序的示例代码:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 9, 4};
bubbleSort(arr);
System.out.println(Arrays.toString(arr));
}
public static void bubbleSort(int[] arr) {
int temp;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
```
这个程序使用冒泡排序算法对一个整数数组进行排序,可以将其作为参考来编写自己的冒泡排序程序。
相关问题
使用java写一个冒泡排序
当然!以下是使用Java编写的冒泡排序算法的示例代码:
```java
public class BubbleSort {
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// 交换arr[j]和arr[j + 1]的位置
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
bubbleSort(arr);
System.out.println("排序后的数组:");
for (int i : arr) {
System.out.print(i + " ");
}
}
}
```
在上述代码中,`bubbleSort` 方法接受一个整数数组作为输入,并使用冒泡排序算法对数组进行排序。`main` 方法中创建一个示例数组,并调用 `bubbleSort` 方法对其进行排序。最后,打印排序后的数组。
希望这可以帮助到您!如果您有任何其他问题,请随时提问。
使用Java写一个冒泡排序
好的,我可以回答这个问题。以下是使用 Java 写的冒泡排序代码:
```
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 3, 8, 4, 2};
bubbleSort(arr);
for (int i : arr) {
System.out.print(i + " ");
}
}
public static void bubbleSort(int[] arr) {
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;
}
}
}
}
}
```
这段代码可以对一个整数数组进行冒泡排序,将数组中的元素从小到大排列。