设计一个BubbleSort类,定义数组int[]={3,1,9,30,7,5,24,15,19}并用冒泡排序对数组元素从小到大排序}
时间: 2024-05-08 12:20:50 浏览: 13
好的,以下是BubbleSort类的实现:
```
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {3, 1, 9, 30, 7, 5, 24, 15, 19};
bubbleSort(arr);
System.out.println(Arrays.toString(arr));
}
public static void bubbleSort(int[] arr) {
int len = arr.length;
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
```
输出结果为:[1, 3, 5, 7, 9, 15, 19, 24, 30]
相关问题
设计一个BubbleSort类。 (1)定义数组int[] arr = { 3, 1, 9, 30,7, 5,24,15,19 }; (2)用冒泡排序对数组元素从大到小排序。
以下是BubbleSort类的示例代码,其中包括了对数组元素从大到小排序的实现:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = { 3, 1, 9, 30, 7, 5, 24, 15, 19 };
// 冒泡排序
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 i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
```
运行结果为:
```
30 24 19 15 9 7 5 3 1
```
定义一个数组{1,2,3,4,5},利用java实现冒泡排序
好的,以下是使用Java实现冒泡排序的示例代码:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
// 执行冒泡排序
bubbleSort(array);
// 打印排序后的数组
for (int num : array) {
System.out.print(num + " ");
}
}
public static void bubbleSort(int[] array) {
int n = array.length;
// 进行 n-1 轮冒泡
for (int i = 0; i < n - 1; i++) {
// 每一轮冒泡将最大的元素放到最后
for (int j = 0; j < n - i - 1; j++) {
if (array[j] > array[j + 1]) {
// 交换相邻两个元素
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
}
```
运行以上代码,输出结果为:`1 2 3 4 5`,表示数组已经按照升序排列完成。
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](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)